小编典典

从XML文档获取指定的Node值

c#

我在遍历XML文档(使用C#)并获取所有必要的值时遇到问题。我成功地浏览了XML文档中所有指定的XmlNodeList,成功地获取了所有XmlNode值,但是我必须获取此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的值的代码:

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和日期的值时遇到问题。


阅读 359

收藏
2020-05-19

共1个答案

小编典典

就像您要从中获取某些东西一样,CNode您也需要为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;
         }
        }
    }
}
2020-05-19