简体   繁体   中英

How to get all child nodes of an XML in C#

I've an XML document like this:

<Columns>
  <Column>
    <Name>A</Name>
    <Width>100</Width>
  </Column>
</Columns>

<Columns>

</Columns>

<Columns>
  <Column>
    <Name>C</Name>
    <Width>300</Width>
  </Column>
  <Column>
    <Name>C1</Name>
    <Width>310</Width>
  </Column>
</Columns>

I'm getting their Name and Width text and store them a List.

var man = new XmlNamespaceManager(xdoc.NameTable);
man.AddNamespace("ns", "http://schemas.microsoft.com/project");
List <string> lstText = new List<string>();
List <List<string>> lst = new List<List<string>>();
XmlNodeList xnList = xdoc.SelectNodes("/ns:Columns/ns:Column", man);

foreach (XmlNode xn in xnList)
        {
           lstText.Add(xn["Name"].InnerText));
           lstText.Add(xn["Width"].InnerText));
        }
lst.Add(lstText);

So, I can only get these values: A and 100, C and 300. I want to get C1 and 310 too. How can I get them?

Edit: Some of Columns has no Column, some of Columns has 1 or more Colums. In this sample, my List has 3 elements:

lst[0][0] = {A, 100}
lst[1][0] = null
lst[2][0] = {C, 300}, lst[2][1] = {C1, 310}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

public class MainClass

{

public static void Main()
{
    XmlDocument mDocument = new XmlDocument();
    XmlNode mCurrentNode;

    mDocument.Load("XPathQuery.xml");
    mCurrentNode = mDocument.DocumentElement;


    XmlNodeList nodeList = mCurrentNode.SelectNodes("*");
    DisplayList(nodeList);
}

static void DisplayList(XmlNodeList nodeList)
{
    foreach (XmlNode node in nodeList)
    {
        RecurseXmlDocumentNoSiblings(node);
    }
}

static void RecurseXmlDocumentNoSiblings(XmlNode root)
{
    if (root is XmlElement)
    {
        Console.WriteLine(root.Name);
        if (root.HasChildNodes)
            RecurseXmlDocument(root.FirstChild);
    }
    else if (root is XmlText)
    {
        string text = ((XmlText)root).Value;
        Console.WriteLine(text);
    }
    else if (root is XmlComment)
    {
        string text = root.Value;
        Console.WriteLine(text);
        if (root.HasChildNodes)
            RecurseXmlDocument(root.FirstChild);
    }
}
static void RecurseXmlDocument(XmlNode root)
{
    if (root is XmlElement)
    {
        Console.WriteLine(root.Name);
        if (root.HasChildNodes)
            RecurseXmlDocument(root.FirstChild);
        if (root.NextSibling != null)
            RecurseXmlDocument(root.NextSibling);
    }
    else if (root is XmlText)
    {
        string text = ((XmlText)root).Value;
        Console.WriteLine(text);
    }
    else if (root is XmlComment)
    {
        string text = root.Value;
        Console.WriteLine(text);
        if (root.HasChildNodes)
            RecurseXmlDocument(root.FirstChild);
        if (root.NextSibling != null)
            RecurseXmlDocument(root.NextSibling);
    }
}

}

    public readonly Dictionary<string, int> XmlValues = new Dictionary<string, int>();
    public void Analyze(XmlDocument xml)
    {
        RecurseXmlDocument(xml.LastChild);
    }

    void RecurseXmlDocument(XmlNode root)
    {
        switch (root.NodeType)
        {
            case XmlNodeType.Element:
                if (root.HasChildNodes)
                    RecurseXmlDocument(root.FirstChild);
                if (root.NextSibling != null)
                    RecurseXmlDocument(root.NextSibling);
                break;

            case XmlNodeType.Text:
                DictionayHelper.AddValue(XmlValues, root.Value);
                break;
        }
    }

Use System.Xml.Linq:

const string name = "Name";
var xml = XDocument.Load(@"P:\athToYour\columns.xml");
var columns = xml.Descendants(name).Select(x => new
{
    Name = x.Value,
    Width = x.ElementsAfterSelf("Width").FirstOrDefault().Value
})
.ToDictionary(x=> x.Name, x=> x.Width);
columns.Dump();

You can do it this way; If you need you can reduce it down to 2 lines.

                var xDoc = XDocument.Load(@"c:\XPathQuery.xml");
        //this query gets Names and widths
        var widths = xDoc.Descendants().Where(x => x.Name.LocalName.Equals("Name")).Select(x => new { Name = x.Value, Width = x.ElementsAfterSelf().First().Value }).ToList();

        //if you want to loop through the collection, you can do like this.
        foreach (var width in widths)
        {
            var name = width.Name;
            var value = width.Width;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM