C# XDocument.Descendants 不返回后代

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11933782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:46:13  来源:igfitidea点击:

XDocument.Descendants not returning descendants

c#.netxmllinq-to-xml

提问by l46kok

<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 nationalListbut it isn't working for me, it skips the foreachloop entirely. What am I doing wrong here?

我想遍历每个节点,nationalList但它对我不起作用,它foreach完全跳过了循环。我在这里做错了什么?

采纳答案by Jon Skeet

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

您不包括命名空间,即"http://www.lge.com/ddc"从父元素默认的命名空间:

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

回答by Henk Holterman

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());
}

回答by Christian Moser

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

问候基督徒

回答by derekadk

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:

如果您不想在所有选择器中都使用 ns 前缀,您还可以在解析 xml 时预先删除命名空间。例如:

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

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