循环遍历 XML 文档 [英] Looping through XML Document

查看:36
本文介绍了循环遍历 XML 文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的方法:

<预><代码>if (File.Exists(@"C:\config.xml")){System.Xml.XmlDocument xd = new System.Xml.XmlDocument();xd.Load(@"C:\config.xml");System.Xml.XmlElement root = xd.DocumentElement;System.Xml.XmlNodeList nl = root.SelectNodes("/config");foreach(nl 中的 System.Xml.XmlNode xnode){字符串名称 = xnode.Name;字符串值 = xnode.InnerText;字符串 nv = 名称 + "|"+ 价值;发送(nv);}

我的 Xml 文档

现在我的方法只返回前 2 个.我在做什么错...

解决方案

使用 System.Xml 命名空间以避免长类型限定,即...

 使用 System.Xml;

然后尝试这样的事情..

 XmlNodeList nl = xd.SelectNodes("config");XmlNode 根 = nl[0];foreach(root.ChildNodes 中的 XmlNode xnode){字符串名称 = xnode.Name;字符串值 = xnode.InnerText;字符串 nv = 名称 + "|"+ 价值;发送(nv);}

我认为你的方法有问题.

a) 我不认为 SelectNodes 应该采用 /config 参数,而应该采用 config.

b) 在选择第一个(也是唯一的 - .Net 中的 XML 文件必须有一个且只有一个根节点)根节点后,您需要遍历根的 ChildNodes.

My Method:


if (File.Exists( @"C:\config.xml"))
   {
    System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
    xd.Load( @"C:\config.xml");
    System.Xml.XmlElement root = xd.DocumentElement;
    System.Xml.XmlNodeList nl = root.SelectNodes("/config");
    foreach (System.Xml.XmlNode xnode in nl)
    {
        string name = xnode.Name;
        string value = xnode.InnerText;
        string nv = name + "|" + value;
        Send(nv);
        }

My Xml Doc

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<config>
<bla>D</bla>
<def>300</def>
<ttOUT>34000</ttOUT>
<num>3800</num>
<pw>help</pw>
<err>1</err>
....and so on
</config>

Now my method returns the first 2 and nothing else. What am i doing wrong...

解决方案

use the System.Xml namespace to avoid long type qualifications ie...

    using System.Xml;

Then try something like this..

    XmlNodeList nl = xd.SelectNodes("config");
    XmlNode root = nl[0];

    foreach (XmlNode xnode in root.ChildNodes)
    {
        string name = xnode.Name;
        string value = xnode.InnerText;
        string nv = name + "|" + value;
        Send(nv);
    }

I believe there is something wrong with your method.

a) I don't think SelectNodes should take the /config argument, rather it should take config.

b) After selecting the first (and only - XML files in .Net must have one and only one root node) root node you need to iterate through the ChildNodes of the root.

这篇关于循环遍历 XML 文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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