簡體   English   中英

如何以編程方式找到特定的 XML 元素?

[英]How can I find a specific XML element programmatically?

我有這塊 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 可能不存在。 所以我需要一種方法來根據“名稱是什么”來查找元素,即以編程方式查找它。 我不能依賴索引是准確的。

您可以使用此代碼從特定元素讀取內部文本:

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());
                           }
                        
                        

                    }
                }

通過利用 .NET 框架版本中直接提供的 XPath 功能,您通常可以在 XML 文檔中找到任何內容。

也許創建一個小的 XPath 解析器助手 class

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

然后像下面這樣調用它以獲取所有名稱等於您需要搜索的名稱的自定義字段

// 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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM