【问题标题】:Problem in reading XML node with unknown root/parent nodes读取具有未知根/父节点的 XML 节点时出现问题
【发布时间】:2010-11-15 14:01:41
【问题描述】:

我一直在尝试读取 xml 文件。我必须提取节点“日期”和“名称”的值,但问题是,它们可能出现在 XML 层次结构中的任何级别。

所以当我尝试使用这段代码时,

        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>

上述代码错误,因为&lt;name&gt;&lt;date&gt; 不是root 的直接子元素。
是否可以假设父/根节点是未知的,仅使用节点的名称,复制值??

【问题讨论】:

    标签: c# .net xml


    【解决方案1】:

    根据您遇到的异常情况,这可能是也可能不是确切的解决方案。但是,我肯定会先检查datename 是否存在,然后再对它们执行.InnerText

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

    【讨论】:

    • 经过必要的基本编辑和解决方法,可以接受答案。 :) @标记。感谢您的宝贵帖子。
    【解决方案2】:

    我会阅读有关 C# 的 XPATH 和 XPATH 以更有效地做到这一点

    http://support.microsoft.com/kb/308333

    http://www.w3schools.com/XPath/xpath_syntax.asp

    这里有一个小方法可以让你轻松获取innerText。

    function string GetElementText(string xml, string node)
    {
        XPathDocument doc = new XPathDocument(xml);
        XPathNavigator nav = doc.CreateNavigator();
    
        XPathExpression expr = nav.Compile("//" + node);
        XPathNodeIterator iterator = nav.Select(expr);
    
        while (iterator.MoveNext())
        {
            // return 1st but there could be more
            return iterator.Current.Value;            
        }
    }
    

    【讨论】:

    • 感谢您宝贵的时间和回答。 :)
    【解决方案3】:

    尝试使用 LINQ:

            string xml = @"<?xml version='1.0' encoding='utf-8'?>
                           <root>
                           <date>12/03/2001</date>
                           <child>
                             <name>Aravind</name>
                             <date>12/03/2000</date>
                           </child>
                           <name>AS-CII</name>
                           </root>";
    
            XDocument doc = XDocument.Parse(xml);
    
            foreach (var date in doc.Descendants("date"))
            {
                Console.WriteLine(date.Value);
            }
    
            foreach (var date in doc.Descendants("name"))
            {
                Console.WriteLine(date.Value);
            }
    
            Console.ReadLine();
    

    Descendants 方法允许您获取所有具有指定名称的元素。

    【讨论】:

    • 你能告诉我应该使用哪个命名空间吗?
    • 添加 System.Xml.Linq 作为参考和使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多