在未知根/父节点读取XML节点问题 [英] Problem in reading XML node with unknown root/parent nodes

查看:190
本文介绍了在未知根/父节点读取XML节点问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图读取XML文件。我要提取节点的日期和名称的价值,但问题是,他们可能会出现在XML层次结构的任何级别。

I have been trying to read an xml file. I have to extract value of nodes "Date" and "Name", but the problem is, they might appear at any level in XML hierarchy.

所以,当我尝试用这个code,

So when I try with this code,

        XmlDocument doc = new XmlDocument();
        doc.Load("test1.xml");
        XmlElement root = doc.DocumentElement;
        XmlNodeList nodes = root.SelectNodes("//*");
        string date;
        string name;

        foreach (XmlNode node in nodes)
        {
                    date = node["date"].InnerText;
                    name = node["name"].InnerText;
        }

和XML文件::

<?xml version="1.0" encoding="utf-8"?>
<root>
<child>
  <name>Aravind</name>
  <date>12/03/2000</date>
</child>
</root>

以上code错误了,因为&LT;名称&gt; &LT;日期&GT; 不对根直接子元素
是它可以假定父/根节点是未知的,只是与节点的名称,复制数值

the above code errors out, as <name> and <date> are not immediate child Elements of root.
is it possible to assume that parent/root nodes are unknown and just with the name of the nodes, copy the values ??

推荐答案

根据您所得到的例外,这可能是也可能不是确切的解决方案。不过,我肯定会检查日期名称存在做之前, .InnerText 在他们身上。

Depending on the exception you are getting, this may or may not be the exact solution. However, I would definitely check that date and name exist before doing a .InnerText on them.

    foreach (XmlNode node in nodes)
    {
                dateNode = node["date"];
                if(dateNode != null)
                    date = dateNode.InnerText;
                // etc.
    }

这篇关于在未知根/父节点读取XML节点问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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