簡體   English   中英

讀取子節點xml

[英]read child nodes xml

這是我嘗試讀取的XML。

<VacancyList xmlns="urn:abc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" generated="2016-04-20T11:42:47" xsi:schemaLocation="http://www.abc.in/dtd/vacancy-list.xsd">
  <Vacancy id="1619993" date_start="2016-04-15" date_end="2016-04-22" reference_number="">
     <Versions>
       <Version language="nb">
         <Title>Marketing Specialist</Title>
         <TitleHeading/>
         <Location>CXCXC</Location>
         <Engagement/>
         <DailyHours/>
         <Region>
            <County id="11">sds</County>
            <County id="1">zxzx</County>
            </Country>
         </Region>
         <Categories>
           <Item type="position-type" id="3909">sER</Item>
           <Item type="duration" id="contract">ss</Item>
           <Item type="extent" id="fulltime">sd</Item>
           <Item type="operating-time" id="day">s</Item>
         </Categories>
       </Version>
     </Versions>

 </Vacancy>

</VacancyList>

我想讀取節點位置,因此在下面的代碼中寫道

XmlDocument xd = new XmlDocument();
        xd.Load("https://abc.in/list.xml");
        XmlNamespaceManager ns = new XmlNamespaceManager(xd.NameTable);
        ns.AddNamespace("msbld", "urn:abc");

        XmlNodeList nodelist = xd.SelectNodes("//msbld:VacancyList", ns);



        if (nodelist != null)
            foreach (XmlNode node in nodelist)
            {
                XmlNode nodelist1 = node.SelectSingleNode("Vacancy");
                if (nodelist1 != null)
                    foreach (XmlNode node1 in nodelist1)
                    {
                       var k = node1.Attributes.GetNamedItem("Location").Value;

                    }
            }

但是我沒有在變量“ node1”中得到任何東西。 如何解決這個問題?

還有沒有更好的解決方案呢?

更新1

我修改了代碼,但我只得到了節點標題。 無法在“位置”的“版本”節點內獲取其他內容。

if (nodelist != null)
            foreach (XmlNode node in nodelist)
            {
                XmlNode nodelist1 = node.SelectSingleNode("//msbld:Vacancy/msbld:Versions",ns);
                if (nodelist1 != null) { 
                    XmlNode nodelist2 = nodelist1.SelectSingleNode("//msbld:Version", ns);
                    foreach (XmlNode node3Node in nodelist2)
                    {
                        var k = node3Node.Attributes.GetNamedItem("Location").Value;
                    }


                }
            }

xmlns="urn:abc"默認的名稱空間 注意,沒有前綴的后代元素隱式繼承了祖先的默認名稱空間。 您還需要使用引用默認名稱空間URI的相同前綴來訪問VacancyLocation

XmlNode nodelist1 = node.SelectSingleNode("msbld:Vacancy", ns);

您更新后的代碼引入了一個完全不同的問題。 /在路徑表達式的開頭始終會引用文檔元素,除非您使用明確將上下文設置為當前活動上下文. /之前,例如:

XmlNode nodelist1 = node.SelectSingleNode(".//msbld:Vacancy/msbld:Versions",ns);

如果只需要Location元素,則可以這樣:

var doc = XElement.Load("path/to/file");
var location = doc.Descendants
    .FirstOrDefault(e => e.Name.LocalName == "Location"));

暫無
暫無

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

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