Alan Schapira
Alan Schapira

Reputation: 1163

Convert multiple nodes in xml to List<string> (C#)

I have the following xml file:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<termsAndConditions>
  <logo>
    logo1.gif
  </logo>
  <link>
    https://www.mysite.co.uk/Terms%20and%20Conditions.pdf
  </link>
  <paragraphs>
    <text>
      I accept that all the information I have provided is truthful and accurate and I understand that all the information I have provided will be checked and verified. I acknowledge that I have read and accepted all the Terms and Conditions of the site’s Parking Regulations, for full details click here.
    </text>
    <text>
      Paragraph 2
    </text>
    <text>
       Paragraph 3
    </text>
    <text>
       Paragraph 4
    </text>
  </paragraphs>
</termsAndConditions>

Now I can convert a node to a string using the following:

XmlDocument doc = new XmlDocument();
doc.Load("\\termConditionsExample.xml");
XmlNode node = doc.DocumentElement.SelectSingleNode("/termsAndConditions/logo");
string myString = node.InnerText;

But how can I do this for the "paragraphs/text" in the xml file to turn them into a List type? I have tried using the different DocumentElement mwthods such as one below, but it does not work:

List<string> paragraphs = new List<string>();
            foreach(var temp in doc.DocumentElement.ChildNodes)
            {
                paragraphs.Add(temp.ToString());
            }

I know this one does not take any arguments so is wrong. I just don't know which one to use...

Upvotes: 0

Views: 1617

Answers (3)

Yacoub Massad
Yacoub Massad

Reputation: 27871

Here is how you can use XPath with the XDocument class:

XDocument document = XDocument.Load(filename);

var result =
    document
        .XPathSelectElements("termsAndConditions/paragraphs/text")
        .Select(x => x.Value.Trim())
        .ToList();

It allows you to select the text elements that are in the specified path only (not all the text elements in the whole xml file).

Make sure you import the System.Xml.XPath namespace like this:

using System.Xml.XPath;

Upvotes: 0

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43946

You could use XmlDocument.SelectNodes and XmlNode.InnerText:

foreach (XmlNode node in doc.SelectNodes("/termsAndConditions/paragraphs/text"))
  paragraphs.Add(node.InnerText.Trim());

Upvotes: 0

StriplingWarrior
StriplingWarrior

Reputation: 156748

I find LINQ-to-XML to be easier to work with for things like this (e.g. XDocument instead of XmlDocument).

var xdoc = XDocument.Load("\\termConditionsExample.xml");
IEnumerable<string> textValues = xdoc.Descendants("text").Select(e => e.Value);

Xml Deserialization may also be an appropriate approach, as C. Knight mentions in comments.

Upvotes: 3

Related Questions