如何使用C#在XML文件中循环遍历子项的子项?

时间:2011-10-13 02:24:35

标签: c# xml xml-parsing

我可以显示版本日期和版本号,但是对于剩下的信息,我希望它输出元素名称,后跟标记中的信息。最后,我希望它能读到:

versionDate: 2011-10-04
versionNumber: 1.0
FirstName: Bob 
LastName: Johnson
PhoneNumber: 123-456-7890
FaxNumber: 111-111-1111
EmailAddress: bjohnson@aol.com
Gender: M
FirstName: Sue 
LastName: Smith
PhoneNumber: 987-654-3210
FaxNumber: 222-222-2222
EmailAddress: ssmith@comcast.net
Gender: F

相反,它显示了这个:

versionDate: 2011-10-04
versionNumber: 1.0
versionDate#text - 2011-10-04Contact info: False#text - 2011-10-04versionNumber#text - 2011-10-04Contact info: False#text - 2011-10-04ContactFirstName - 2011-10-04Contact info: False#text - 2011-10-04ContactFirstName - 2011-10-04Contact info: False#text - 2011-10-04ContactFirstName - 2011-10-04Contact info: False#text - 2011-10-04ContactFirstName - 2011-10-04Contact info: False#text - 2011-10-04ContactFirstName - 2011-10-04Contact info: 

我已经尝试制作另一个XmlNodeList,它是孩子的​​孩子,但它不喜欢语法,所以我需要知道如何进入下一级信息。

我已在下面添加了XML和C#文件。

<Contacts>
  <versionDate>2011-10-04</versionDate>
  <versionNumber>1.0</versionNumber>
  <Contact Gender ="M">
    <FirstName>Bob</FirstName>
    <LastName>Johnson</LastName>
    <PhoneNumber>123-456-7890</PhoneNumber>
    <FaxNumber>111-111-1111</FaxNumber>
    <EmailAddress>bjohnson@aol.com</EmailAddress>
  </Contact>
  <Contact Gender ="F">
    <FirstName>Sue</FirstName>
    <LastName>Smith</LastName>
    <PhoneNumber>987-654-3210</PhoneNumber>
    <FaxNumber>222-222-2222</FaxNumber>
    <EmailAddress>ssmith@comcast.net</EmailAddress>
  </Contact>
</Contacts>


public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    string results = "";

    private void button1_Click(object sender, EventArgs e)
    {

        string fileName = Application.StartupPath + "\\XMLFile1.xml";
        XmlDocument xmlDoc = new XmlDocument();

        xmlDoc.Load(fileName);
        XmlElement elm = xmlDoc.DocumentElement;

        results += elm.FirstChild.Name + ": " + elm.FirstChild.InnerText + Environment.NewLine;
        results += elm.FirstChild.NextSibling.Name + ": " + elm.FirstChild.NextSibling.InnerText + Environment.NewLine;


        XmlNodeList contactInfo = elm.ChildNodes;
        for (int count = 0; count < contactInfo.Count; count++)
        {
            results += (contactInfo[count].Name);
              results += (contactInfo[count].FirstChild.Name + " - " + contactInfo[0].FirstChild.InnerText);
            results += ("Contact info: " + contactInfo[0].FirstChild.HasChildNodes.ToString());
            XmlNodeList contactProperties = contactInfo[0].ChildNodes;

            for (int counter = 0; counter < contactProperties.Count; counter++)
            {
                results += (contactProperties[counter].Name + " - " + contactProperties[counter].InnerText);

            }
        }

        textBox1.Text += results;
    }

}

任何和所有帮助将不胜感激!谢谢!

2 个答案:

答案 0 :(得分:1)

递归应该有效:

public string CompileResults(XElement e)
{
    string retVal = String.Format("{0}:{1} ", e.Name, e.Value);

    foreach (XAttribute xa in e.Attributes())
        retVal += String.Format("{0}:{1} ", xa.Name, xa.Value);

    foreach (XElement xe in e.Elements())
        retVal += CompileResults(xe); ;
    return retVal;
}

private void button1_Click(object sender, EventArgs e)
{
    string fileName = Application.StartupPath + "\\XMLFile1.xml";
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(fileName);

    string results = CompileResults(xmlDoc.FirstChild);
}

答案 1 :(得分:0)

我会做这样的事情:

public static void DumpXml(XElement root, TextWriter writer)
{
    if (root.HasElements)
    {
        foreach (var child in root.Elements())
        {
            DumpXml(child, writer);
        }
    }
    else
    {
        writer.WriteLine("{0}: {1}", root.Name, root.Value);
    }

    foreach (var attr in root.Attributes())
    {
        writer.WriteLine("{0}: {1}", attr.Name, attr.Value);
    }
}

然后使用它:

var doc = XDocument.Load(xmlPath);
var writer = new StringWriter();
DumpXml(doc.Root, writer);
var result = writer.ToString();