【问题标题】:How can I find a specific XML element programmatically?如何以编程方式找到特定的 XML 元素?
【发布时间】:2020-11-27 10:39:29
【问题描述】:

我有这块 XML

<EnvelopeStatus>

  <CustomFields>
     <CustomField>
        <Name>Matter ID</Name>
        <Show>True</Show>
        <Required>True</Required>
        <Value>3</Value>
     </CustomField>
     <CustomField>
        <Name>AccountId</Name>
        <Show>false</Show>
        <Required>false</Required>
        <Value>10804813</Value>
        <CustomFieldType>Text</CustomFieldType>
     </CustomField>

我有以下代码:

// TODO find these programmatically rather than a strict path.
var accountId = envelopeStatus.SelectSingleNode("./a:CustomFields", mgr).ChildNodes[1].ChildNodes[3].InnerText;
var matterId = envelopeStatus.SelectSingleNode("./a:CustomFields", mgr).ChildNodes[0].ChildNodes[3].InnerText;

问题是,有时带有“Matter ID”的 CustomField 可能不存在。所以我需要一种方法来根据“名称是什么”来查找元素,即一种程序化的查找方式。我不能指望索引是准确的。

【问题讨论】:

    标签: c# xml xpath .net-core


    【解决方案1】:

    您可以使用此代码从特定元素读取内部文本:

    XmlDocument doc = new XmlDocument();
    doc.Load("your.xml");
    
    XmlNodeList Nodes= doc.SelectNodes("/EnvelopeStatus/CustomField");
    if (((Nodes!= null) && (Nodes.Count > 0)))
                    {
                        foreach (XmlNode Level1 in Nodes)
                        {
                              if (Level1.ChildNodes[1].Name == "name")
                                {
                                 string text = Convert.ToInt32(Level1.ChildNodes[1].InnerText.ToString());
                               }
                            
                            
    
                        }
                    }
    

    【讨论】:

      【解决方案2】:

      通过利用 .NET Framework 版本中直接提供的 XPath 功能,您通常可以在 XML 文档中找到任何内容。

      也许创建一个小的 XPath 解析器帮助类

      public class EnvelopeStatusParser
      {
          public XmlNodeList GetNodesWithName(XmlDocument doc, string name)
          {
              return doc.SelectNodes($"//CustomField[Name[text()='{name}']]");
          }
      }
      

      然后像下面这样调用它以获取所有 Name 等于您需要搜索的内容的 CustomFields

      // Creating the XML Document in some form - here reading from file
      XmlDocument doc = new XmlDocument();
      doc.Load(@"envelopestatus.xml");
      
      var parser = new EnvelopeStatusParser();
      
      var matchingNodes = parser.GetNodesWithName(doc, "Matter ID");
      Console.WriteLine(matchingNodes);
      
      matchingNodes = parser.GetNodesWithName(doc, "NotHere");
      Console.WriteLine(matchingNodes);
      

      周围有许多 XPath 备忘单 - 就像来自 LaCoupa 的这个 - xpath-cheatsheet 这对于在 XML 结构上充分利用 XPath 很有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-06
        • 1970-01-01
        • 1970-01-01
        • 2017-05-06
        • 1970-01-01
        • 2011-10-09
        • 1970-01-01
        • 2014-02-02
        相关资源
        最近更新 更多