【问题标题】:How to simplyfy this function with linq-to-xml query?如何使用 linq-to-xml 查询简化此功能?
【发布时间】:2021-08-14 21:03:09
【问题描述】:

我已经阅读了所有或几乎所有标签 linq-to-xml 以在我的例程中找到 where 子句的正确用法...但我无法找到解决方案... 有人可以帮帮我吗?

按照我丑陋的代码...

    public string ExtractTag(string fileName, string tagName)
    {
        string fileBuffer = "";
        using (StreamReader sr = new StreamReader(fileName))
        {
            fileBuffer = sr.ReadToEnd();
        }

        XDocument doc = XDocument.Parse(fileBuffer);
        //Debug.WriteLine("doc.DescendantNodes().Count()=" + doc.DescendantNodes().Count());

        foreach (XNode node in doc.DescendantNodes())
        {
            if (node is XElement)
            {
                XElement element = (XElement)node;
                // Search the root node
                if (element.Name.LocalName.Equals("FatturaElettronica"))
                {
                    // Enumerate all nodes of "FatturaElettronica"
                    IEnumerable<XElement> de = from el in element.Descendants() select el;
                    foreach (XElement el in de)
                    {
                        if (string.Compare(el.Name.ToString(), tagName) == 0)
                        {
                            return el.Value;
                        }
                    }
                }
            }
        }
        return string.Empty;
    }

【问题讨论】:

  • 有什么问题?您当前的代码是否有效?有性能问题吗?您能否分享一个完整的minimal reproducible example,显示当前代码未按要求执行的 XML?为什么只检查本地名称而不检查命名空间?

标签: linq-to-xml where-clause


【解决方案1】:

据我了解,您对代码的结果感到满意,并使用给定名称(如果存在)搜索 FatturaElettronica 的第一个后代。你可以用不同的和更短的方式来写。即:

public string ExtractTag(string fileName, string tagName)
{
    XDocument doc = XDocument.Load(fileName);
    var node = doc
        .Descendants("FatturaElettronica")
        .Descendants(tagName)
        .FirstOrDefault();
    return node == null ? string.Empty : node.Value;
}

或者您可以选择使用更短的 XPath 方法(我会发送 FatturaElettronica 作为参数而不是硬编码):

//Sample call
var result = ExtractTag(@"c:\folder\myfile.xml", "//FatturaElettronica//id"); 

public string ExtractTag(string fileName, string xpath)
{
    XDocument doc = XDocument.Load(fileName);
    var node = doc.XPathSelectElement(xpath);
    return node == null ? string.Empty : node.Value;
}

 

【讨论】:

  • 太棒了!你懂我的需要!我更喜欢第一个解决方案,因为我会在所有文档中找到“Fattura Elettronica”......非常感谢......
猜你喜欢
  • 2011-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多