用c#打印xml节点列表

编程入门 行业动态 更新时间:2024-10-25 10:21:46
本文介绍了用c#打印xml节点列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我需要一些帮助来获取 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-25 11:22:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1115315.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:节点   列表   xml

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!