Home > Mobile >  Parse XML with no Nodes - c#
Parse XML with no Nodes - c#

Time:04-26

I am new to XML and Linq and am trying to read the contents of an XML file into a list. However the file is not split into nodes which I have seen plenty of examples for online, they are all separate elements - see example below.

<ProductProfile>
  <Version>1.3</Version>
  <ProductInfo>
    <PartNum>3354</PartNum>
    <Rev>343</Rev>
    <serialNum>2323</serialNum>
    <RevLevel>23243</RevLevel>
    <Products>8258</Products>
    <Description>8258 long</Description>
  </ProductInfo>
  <Customer>
    <Name>qwerty</Name>
  </Customer><ProductProfile/>

The below code returns the contents but they are all added to the list as one string as opposed to separate items. Is there some way to separate them or should I be using a different way to read the file?

string pathfile = @"C:\filename";

        XPathDocument doc = new XPathDocument(pathfile);
        XPathNavigator nav = doc.CreateNavigator();

        // Compile a standard XPath expression
        XPathExpression expr;
        expr = nav.Compile("//");
        XPathNodeIterator iterator = nav.Select(expr);

        // Method to clear WPF textboxes
        loadClearGenerator();
        List<string> elementContents = new List<string>();
        try
        {
            while (iterator.MoveNext())
            {
                XPathNavigator nav2 = iterator.Current.Clone();
                elementContents.Add(nav2.Value.ToString());
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

CodePudding user response:

Assuming you're just trying to get all non-whitespace text node values in a list, I'd just use LINQ to XML rather than XPath. Here's a complete program:

using System.Xml.Linq;

var doc = XDocument.Load("Test.xml");
var textNodeValues = doc
    .DescendantNodes()
    .OfType<XText>()
    .Select(text => text.Value)
    .Where(text => !string.IsNullOrWhiteSpace(text))
    .ToList();

foreach (string value in textNodeValues)
{
    Console.WriteLine(value);
}

Output with your sample XML (modified to be valid XML):

1.3
3354
343
2323
23243
8258
8258 long
qwerty

In this case, you don't even need the .Where(text => !string.IsNullOrWhiteSpace(text)) call - it just means if you've loaded a document preserving ignorable whitespace, it would ignore those nodes when constructing the list.

  • Related