简体   繁体   中英

How can I find a specific XML element programmatically?

I have this chunk of 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>

I have this code below:

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

The problem is, sometimes the CustomField with 'Matter ID' might not be there. So I need a way to find the element based on what 'Name is', ie a programmatic way of finding it. I can't rely on indexes being accurate.

You can use this code to read innertext from a specific element:

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

                    }
                }

You can often find anything in a XML document by utilizing the XPath capabilities that is available directly in the .NET Framework versions.

Maybe create a small XPath parser helper class

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

and then call it like below to get all CustomFields which have a Name that equals what you need to search for

// 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);

There exist numerous XPath cheat sheets around - like this one from LaCoupa - xpath-cheatsheet which can be quiet helpful to fully utilize XPath on XML structures.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM