-4

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

Xavier C.
  • 65
  • 8
  • I have some code that actually does do this, if you are interested I can post it. I created a web application that will read an input file from NIST and update the corresponding local database with their latest vulnerability information. The source file from them is XML so I have to parse out their data and populate my database fields with their information. – bbcompent1 May 15 '17 at 14:10
  • *without XPath (so XmlDocument or XmlReader*?! Why would you want to discount ways to parse the XML correctly? – Liam May 15 '17 at 14:10
  • 1
    Possible duplicate of [How to read a particular node from xml in C#?](http://stackoverflow.com/questions/16147142/how-to-read-a-particular-node-from-xml-in-c) – Liam May 15 '17 at 14:11
  • @bbcompent1 yes it would be nice ! – Xavier C. May 15 '17 at 14:13
  • @XavierC. I updated my answer. – Hossein Narimani Rad May 15 '17 at 15:42

2 Answers2

1

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.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
0

Do you want "test"? Try following :

            string input =
                "<foo>" +
                  "<bar><para> test </para> </bar>" +
                  "<bar>text</bar>" +
                  "<bar>stackoverflow</bar>" +
                "</foo>";


            XDocument doc = XDocument.Parse(input);

            List<string> bars = doc.Descendants("bar").Where(x => x.NextNode != null).Select(x => (string)((XElement)x.NextNode)).ToList();
jdweng
  • 33,250
  • 2
  • 15
  • 20
  • 1
    I don't want test because it's not in bar but in para, I edited my first post. Sorry if it was confuse – Xavier C. May 15 '17 at 14:18