XDocument.Descendants not returning descendants

╄→尐↘猪︶ㄣ 提交于 2019-12-18 18:35:10

问题


<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <SetNationalList xmlns="http://www.lge.com/ddc">
      <nationalList>
        <portnumber>6000</portnumber>
        <slaveaddress>7000</slaveaddress>
        <flagzone>2</flagzone>
        <flagindivisual>5</flagindivisual>
        <flagdimming>3</flagdimming>
        <flagpattern>6</flagpattern>
        <flaggroup>9</flaggroup>
      </nationalList>
    </SetNationalList>
  </s:Body>
</s:Envelope>

XDocument xdoc = XDocument.Parse(xml);
foreach (XElement element in xdoc.Descendants("nationalList"))
{
   MessageBox.Show(element.ToString());
}

I'd like to iterate through every nodes under nationalList but it isn't working for me, it skips the foreach loop entirely. What am I doing wrong here?


回答1:


You're not including the namespace, which is "http://www.lge.com/ddc", defaulted from the parent element:

XNamespace ns = "http://www.lge.com/ddc";
foreach (XElement element in xdoc.Descendants(ns + "nationalList"))
{
    ...
}



回答2:


You have to use the namespace:

// do _not_ use   var ns = ... here.
XNameSpace ns = "http://www.lge.com/ddc";

foreach (XElement element in xdoc.Descendants(ns + "nationalList")
{
      MessageBox.Show(element.ToString());
}



回答3:


If you don't want to have to use the ns prefix in all the selectors you can also remove the namespace upfront when parsing the xml. eg:

string ns = "http://www.lge.com/ddc";
XDocument xdoc = XDocument.Parse(xml.Replace(ns, string.Empty));

foreach (XElement element in xdoc.Descendants("nationalList")
...



回答4:


It is correct that you have to include the namespace, but the samples above do not work unless you put the namespace in curly braces:

XNameSpace ns = "http://www.lge.com/ddc";

foreach (XElement element in xdoc.Descendants("{" + ns + "}nationalList")
{
      MessageBox.Show(element.ToString());
}

Greetings Christian



来源:https://stackoverflow.com/questions/11933782/xdocument-descendants-not-returning-descendants

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!