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

发布于 2024-12-09 11:01:48 字数 3633 浏览 0 评论 0原文

我可以显示版本日期和版本号,但对于其余信息,我希望它输出元素名称,后跟标签内的信息。最后,我希望它读到类似的内容:

versionDate: 2011-10-04
versionNumber: 1.0
FirstName: Bob 
LastName: Johnson
PhoneNumber: 123-456-7890
FaxNumber: 111-111-1111
EmailAddress: [email protected]
Gender: M
FirstName: Sue 
LastName: Smith
PhoneNumber: 987-654-3210
FaxNumber: 222-222-2222
EmailAddress: [email protected]
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>[email protected]</EmailAddress>
  </Contact>
  <Contact Gender ="F">
    <FirstName>Sue</FirstName>
    <LastName>Smith</LastName>
    <PhoneNumber>987-654-3210</PhoneNumber>
    <FaxNumber>222-222-2222</FaxNumber>
    <EmailAddress>[email protected]</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;
    }

}

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

I can get the version date and version number to show up, but for the remaining information I want it to output the element name followed by the information within the tag. In the end I'd like it to read something like:

versionDate: 2011-10-04
versionNumber: 1.0
FirstName: Bob 
LastName: Johnson
PhoneNumber: 123-456-7890
FaxNumber: 111-111-1111
EmailAddress: [email protected]
Gender: M
FirstName: Sue 
LastName: Smith
PhoneNumber: 987-654-3210
FaxNumber: 222-222-2222
EmailAddress: [email protected]
Gender: F

Instead, it's displaying this:

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: 

I've tried making another XmlNodeList that's a child of the child, but it's not liking the syntax, so I need to know how to get down to the next level of information.

I have attached the XML and C# file below.

<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>[email protected]</EmailAddress>
  </Contact>
  <Contact Gender ="F">
    <FirstName>Sue</FirstName>
    <LastName>Smith</LastName>
    <PhoneNumber>987-654-3210</PhoneNumber>
    <FaxNumber>222-222-2222</FaxNumber>
    <EmailAddress>[email protected]</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;
    }

}

Any and all help will be greatly appreciated! Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

初懵 2024-12-16 11:01:48

递归应该有效:

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);
}

Recursion should work:

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);
}
迎风吟唱 2024-12-16 11:01:48

我会做这样的事情:

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();

I'd do something like this:

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);
    }
}

Then use it:

var doc = XDocument.Load(xmlPath);
var writer = new StringWriter();
DumpXml(doc.Root, writer);
var result = writer.ToString();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文