用c#打印xml节点列表 [英] printing list of xml nodes in c#

查看:37
本文介绍了用c#打印xml节点列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助来获取 xml 节点列表并打印它们.

I am need bit of help on getting list of xml nodes and printing them.

我的代码如下:

        XmlDocument doc = new XmlDocument();
        doc.Load("To44532.xml");
        XmlNode xn = doc.DocumentElement;
        foreach (XmlNode xn2 in xn)
        { Console.WriteLine(xn2); }
        Console.ReadLine();

我是 C# 新手,请提前接受我的歉意,因为我问了这个基本问题.所以我想要完整的节点列表,然后在输出中打印它们.

I am new to c# please accept my apologies in advance for asking this basic question. So I wanted full list of nodes and then printing them in output.

我最终得到了这段代码,因为我想调试其他代码之一.这个想法是我想在 winforms 中显示特定的节点.我试过 if 语句,例如:

I ended up with this piece of code because I wanted to debug one of the other code. The idea was that I wanted to display specific nodes in winforms. I tried if statement e.g. :

        foreach (XmlNode node in doc.DocumentElement)
        {
            if (node.Equals("DbtItm"))
            { ..... }

能否请您建议实现它的最佳方法是什么?

Could you please advise whats the best way to achieve it?

推荐答案

您可以按名称选择 XML 节点.

You can select XML Nodes by Name.

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
 <book category="cooking">
   <title lang="en">Everyday Italian</title>
   <author>Giada De Laurentiis</author>
   <year>2005</year>
   <price>30.00</price>
</book>
<book category="children">
   <title lang="en">Harry Potter</title>
   <author>J K. Rowling</author>
   <year>2005</year>
   <price>29.99</price>
</book>
<book category="web">
   <title lang="en">Learning XML</title>
   <author>Erik T. Ray</author>
   <year>2003</year>
   <price>39.95</price>
 </book>
</bookstore>

例如,从上述 xml 中仅获取书籍作者和书籍年份.

For example to get only book author and book year from as above xml.

        XmlDocument xml = new XmlDocument();
        xml.Load("XMLFile1.xml"); 

        XmlNodeList xnList = xml.SelectNodes("/bookstore/book");
        foreach (XmlNode xn in xnList)
        {
            string author = xn["author"].InnerText;
            string year = xn["year"].InnerText;
            Console.WriteLine(author+"-"+year);
        }

这篇关于用c#打印xml节点列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆