簡體   English   中英

從XML文檔獲取指定的節點值

[英]Getting specified Node values from XML document

我在瀏覽XML文檔(使用C#)時遇到問題,並獲得所有必要的值。 我成功瀏覽了XML文檔中所有指定的XmlNodeLists,成功獲取了所有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和Date的值時遇到問題。

就像你從CNode獲得一些東西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;
         }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM