从 XML 文档中获取指定的节点值 [英] Getting specified Node values from XML document

查看:43
本文介绍了从 XML 文档中获取指定的节点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在浏览 XML 文档(使用 C#)并获取所有必要值时遇到问题.我成功遍历了 XML 文档中所有指定的 XmlNodeLists,成功获取了里面的所有 XmlNode 值,但是我必须获取这个 XmlNodeList 之外的一些值.

I have a problem going through an XML document (with C#) and get all the necessary values. I successfully go through all specified XmlNodeLists in the XML document, successfully get all XmlNode values inside, but I have to get some values outside of this XmlNodeList.

例如:

<?xml version="1.0" encoding="UTF-8" ?>
<Element xsi:schemaLocation="http://localhost/AML/CaseInvestigationMangement/Moduli/XmlImportControls/xsdBorrow.xsd xsd2009027_kor21.xsd" Kod="370" xmlns="http://localhost/AML/CaseInvestigationMangement/Moduli/XmlImportControls/xsdBorrow.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
/2001/XMLSchema-instance">
    <ANode>
        <BNode>
            <CNode>
                <Example>
                    <Name>John</Name>
                    <NO>001</NO>
                </Example>
            </CNode>
        </BNode>
        <ID>1234</ID>
        <Date>2011-10-01</Date>
    </ANode>
    <ANode>
        <BNode>
            <CNode>
                <Example>
                    <Name>Mike</Name>
                    <NO>002</NO>
                </Example>
            </CNode>
        </BNode>
        <ID>5678</ID>
        <Date>2011-03-31</Date>
    </ANode>
</Element>

这是获取 XML 文档中每个找到的 ANode 中节点 Name 和 NO 值的代码:

This is the code that gets values for nodes Name and NO in every found ANode in the XML document:

XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); //myXmlString is the xml file in string //copying xml to string: string myXmlString = xmldoc.OuterXml.ToString();
XmlNodeList xnList = xml.SelectNodes("/Element[@*]/ANode/BNode/CNode");
foreach (XmlNode xn in xnList)
{
  XmlNode example = xn.SelectSingleNode("Example");
    if (example != null)
    {
        string na = example["Name"].InnerText;
        string no = example["NO"].InnerText;
    }
}

现在我在获取 ID 和日期的值时遇到问题.

Now I have a problem getting values for ID and Date.

推荐答案

就像你从 CNode 获取一些东西一样,你也需要为 ANode

Just like you do for getting something from the CNode you also need to do for the ANode

XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
  XmlNode anode = xn.SelectSingleNode("ANode");
    if (anode!= null)
    {
        string id = anode["ID"].InnerText;
        string date = anode["Date"].InnerText;
        XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
        foreach (XmlNode node in CNodes)
        {
         XmlNode example = node.SelectSingleNode("Example");
         if (example != null)
         {
            string na = example["Name"].InnerText;
            string no = example["NO"].InnerText;
         }
        }
    }
}

这篇关于从 XML 文档中获取指定的节点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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