我有以下 XML,我一直在尝试 Descendents().Descendents().Descendents 来检索元素值,但我无法让它工作。
我想返回在 PersonID 的第一个元素中找到的第一个值。
这是一个字符串,所以我这样做:
XDocument XDoc = XDocument.Parse(XmlString);
<Root>
<Code>200001</Code>
<MsgType>106</MsgType>
<PersonData>
<MSG>
<NewDataSet xmlns="PersonInstances">
<PersonInstances>
<PersonInstanceId>1</PersonInstanceId>
<PersonId>400</PersonId>
<Status>210005</Status>
<DateChanged>2009-10-20T11:53:00+01:00</DateChanged>
</PersonInstances>
<PersonInstances>
<PersonInstanceId>2</PersonInstanceId>
<PersonId>400</PersonId>
<Status>210005</Status>
<DateChanged>2009-10-20T12:13:00+01:00</DateChanged>
</PersonInstances>
<PersonInstances>
<PersonInstanceId>3</PersonInstanceId>
<PersonId>400</PersonId>
<Status>210005</Status>
<DateChanged>2009-10-20T15:28:00+01:00</DateChanged>
</PersonInstances>
<PersonInstances>
<PersonInstanceId>4</PersonInstanceId>
<PersonId>400</PersonId>
<Status>210005</Status>
<DateChanged>2009-10-20T15:32:00+01:00</DateChanged>
</PersonInstances>
<PersonInstances>
<PersonInstanceId>5</PersonInstanceId>
<PersonId>400</PersonId>
<Status>210005</Status>
<DateChanged>2009-10-21T10:49:00+01:00</DateChanged>
</PersonInstances>
<PersonInstances>
<PersonInstanceId>6</PersonInstanceId>
<PersonId>400</PersonId>
<Status>210005</Status>
<DateChanged>2009-10-21T17:15:00+01:00</DateChanged>
</PersonInstances>
<PersonInstances>
<PersonInstanceId>7</PersonInstanceId>
<PersonId>400</PersonId>
<Status>210005</Status>
<DateChanged>2009-10-22T10:06:00+01:00</DateChanged>
</PersonInstances>
<PersonInstances>
<PersonInstanceId>8</PersonInstanceId>
<PersonId>400</PersonId>
<Status>210005</Status>
<DateChanged>2009-10-22T16:01:00+01:00</DateChanged>
</PersonInstances>
</NewDataSet></MSG></PersonData></Root>
最佳答案
实际上你做错的是你没有在你的获取代码中包含命名空间:
var el = (element.Descendants(XNamespace.Get("PersonInstances") +
"PersonId").FirstOrDefault()).Value;
使用它,它会起作用。
但是让我给你一个关于命名空间的简短信息:
<Persons xlmns="something">
<Person>
<Name>John</Name>
</Person>
</Person>
在此示例中,命名空间适用于所有后代,但如果您想排除某些后代
<Persons xlmns="something">
<Person>
<Name>John</Name>
<LastName xmlns="">Usher</LastName>
</Person>
</Person>
现在 LastName 将从这个命名空间(某物)中排除
但是如果这对你来说很难,那么你可以使用前缀来做同样的事情,而且麻烦更少:
<pre:Persons xlmns:pre="something">
<pre:Person>
<pre:Name>John</Name>
</Person>
</Person>
但是如果你想将所有后代包含到这个命名空间中,你应该在所有后代中使用前缀,如上例所示
如果你想从中排除一些元素:
<pre:Persons xlmns:pre="something">
<Person>
<pre:Name>John</Name>
</Person>
</Person>
然后只需删除前缀即可。
你也可以对属性做同样的事情:
<pre:Persons xlmns:pre="something">
<pre:Person>
<pre:Name pre:Value="Yahoo">John</pre:Name>
</Person>
</Person>
如果是这样的话,您每次想要获取具有命名空间的内容时都需要在代码中指明命名空间。
关于c# - 返回 XDocument 深处的元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1608070/