Search code examples
c#xmlparsingxml-parsingxmlreader

How to get the String of a XML node in C#


enter code herein the XML document :

<foo>
  <bar><para> test </para> </bar>
  <bar>text</bar>
  <bar>stackoverflow</bar>
</foo>

I am trying to parse it and only get the Strings in bar; by using this way:

[function where node is the foo]

foreach (XmlNode subNode in node.ChildNodes)
{

 if (subNode.Name == "bar")
 {
    if (!String.IsNullOrWhiteSpace(subNode.InnerText))
     Debug.WriteLine(subNode.Name + " - " subNode.InnerText);
 }

}

However it gives me test

Thanks


Solution

  • This is what you are looking for (EDITTED based on you updated question)

    XDocument doc = XDocument.Load(path to your xml file);
    XNamespace ns = "http://docbook.org/ns/docbook";
    
    var result = doc.Root.Descendants(ns + "para")
                         .Where(x => x.FirstNode.NodeType == System.Xml.XmlNodeType.Text)
                         .Select(x => x.Value)
                         .ToList();
    

    In your updated xml I see you are using a namespace so the name of your node is not para but it's theNameSpace + "para". The namespace is defined in the first line of your xml file. Also you can see this sample too.