17

Is there a simple way, to get all nodes from an xml document? I need every single node, childnode and so on, to check if they have certain attributes.

Or will I have to crawl through the document, asking for childnodes?

3

8 Answers 8

28

In LINQ to XML it's extremely easy:

XDocument doc = XDocument.Load("test.xml"); // Or whatever
var allElements = doc.Descendants();

So to find all elements with a particular attribute, for example:

var matchingElements = doc.Descendants()
                          .Where(x => x.Attribute("foo") != null);

That's assuming you wanted all elements. If you want all nodes (including text nodes etc, but not including attributes as separate nodes) you'd use DescendantNodes() instead.

EDIT: Namespaces in LINQ to XML are nice. You'd use:

var matchingElements = doc.Descendants()
                          .Where(x => x.Attribute(XNamespace.Xmlns + "aml") != null);

or for a different namespace:

XNamespace ns = "http://some.namespace.uri";

var matchingElements = doc.Descendants()
                          .Where(x => x.Attribute(ns + "foo") != null);
3
  • @Jeff: Do you mean in terms of using an indexer instead of a method call to get an attribute? If so, fixed. If not, I'm confused...
    – Jon Skeet
    Commented Sep 19, 2011 at 7:34
  • Yeah, that's what I meant. :) Commented Sep 19, 2011 at 7:39
  • Excellent. Abit unrelated, but how would i check for attributes, which have a namespace in their name? Like: xmlns:aml? It says I can't have :'s in my attribute name.
    – Nicolai
    Commented Sep 19, 2011 at 7:50
7

see here: Iterating through all nodes in XML file

shortly:

 string xml = @"
    <parent>
      <child>
        <nested />
      </child>
      <child>
        <other>
        </other>
      </child>
    </parent>
    ";

  XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
  while (rdr.Read())
  {
    if (rdr.NodeType == XmlNodeType.Element)
    {
      Console.WriteLine(rdr.LocalName);
    }
  }
1
  • 3
    This method is generally very, very fast compared with XDocument and other DOM-like methods.
    – Abel
    Commented Sep 19, 2011 at 7:22
7

In my opinion the simplest solution is using XPath. Also this works if you have .NET 2:

var testDoc = new XmlDocument();
testDoc.LoadXml(str);
var tmp = testDoc.SelectNodes("//*"); // match every element
1
  • 2
    Get all nodes by attribute name: var pnNodes = testDoc.SelectNodes("//*[@AttributeName]"); Commented Mar 21, 2018 at 23:16
3

XDocument.Descendants will return you all the nodes in a flat enumerable.

1

Check out LINQ to XML. That does what you need.

http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx

You can use the SelectMany extension for example.

But if you want to check the values you can just use LINQ to create where-statements.

0
public void AddWithChildren(XmlNode xnod, Int32 intLevel) //,XmlDocument xmlDoc
    {  
        List<IEnumerable> item = new List<IEnumerable>();
        XmlNode xnodWorking;
        String strIndent = new string('-', 2 * intLevel);
        String strIndent1 = new string('@', 2 * intLevel);
        if (xnod.NodeType == XmlNodeType.Element)
        {
            item.Add(new ListXML(strIndent + xnod.Name, strIndent + xnod.Name, ""));
            XmlNamedNodeMap mapAttributes = xnod.Attributes;
            foreach (XmlNode xnodAttribute in mapAttributes)
            {
                item.Add(new ListXML(strIndent1 + xnodAttribute.Name, strIndent1 + xnodAttribute.Name, ""));
            }
            if (xnod.HasChildNodes)
            {
                xnodWorking = xnod.FirstChild;
                while (xnodWorking != null)
                {
                    AddWithChildren(xnodWorking, intLevel + 1);
                    xnodWorking = xnodWorking.NextSibling;
                }
            }
        }
    }
0
  protected void Page_Load(object sender, EventArgs e)
  {

            XmlDocument document = new XmlDocument();

            string xmlStr;
            using (var wc = new WebClient())
            {
                xmlStr = wc.DownloadString("test.xml");
            }

            var xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(xmlStr);

            XmlNode xnod = xmlDoc.DocumentElement;

           AddWithChildren(xnod, 1);
 }
1
  • Code dumps without explanation are rarely helpful. Please consider adding some context to your answer.
    – Chris
    Commented Oct 9, 2014 at 14:31
0
string AttrNameerr = "err";//find error code in xml
XmlReader rdr = XmlReader.Create(new stem.IO.StringReader(somesXMLtring));//somesXMLtring is xml in string variable we want to find attribute in.
while (rdr.Read())
{
    if (rdr.NodeType == XmlNodeType.Element)
    {
      //Found the new element, now check if the required attribute is present or not. if not, ignore, if yes then display the same
      string val = rdr.GetAttribute(AttrNameerr);//AttrNameerr is name of attribute we need to get value of which. here we are searching for error code stored as value of 'err' attribute

        if (val != null)
          textBox.Text = strResult = "error = " + rdr.GetAttribute(AttrNameerr);

    }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.