如何从 XDocument 中提取特定元素?
我有以下 XDocument:
<SomeDoc Id="73" Protocol="rahrah" xmlns="http://schemas.company.com/rah/rah2/2005/">
<Prop1>11111</Prop1>
<Prop2>77777</Prop2>
<Prop3>88888</Prop3>
</SomeDoc>
我想提取 Prop1 中的值。
我使用以下代码:
var prop1 = xml.Element("Prop1");
但是 prop1 被设置为 null。我是否试图正确提取元素?
I have the following XDocument:
<SomeDoc Id="73" Protocol="rahrah" xmlns="http://schemas.company.com/rah/rah2/2005/">
<Prop1>11111</Prop1>
<Prop2>77777</Prop2>
<Prop3>88888</Prop3>
</SomeDoc>
And I want to extract the value in Prop1.
I use the following code:
var prop1 = xml.Element("Prop1");
But prop1 is being set to null. Am I trying to extract the element correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我假设
xml
是XDocument
对象本身。XDocument
对象包含根元素,而不是其子元素。您需要编写xml.Root.Element("Prop1");
。编辑:您还需要包含名称空间,如下所示:
I'm assuming that
xml
is theXDocument
object itself.An
XDocument
object contains the root element, not its children. You need to writexml.Root.Element("Prop1");
.EDIT: You also need to include the namespace, like this:
您可以发布用于填充 xml 变量的代码吗?
我的疯狂猜测是 XDocument 没有将 xml 片段识别为有效文档。我认为 XDocument 需要
根节点。您可能需要使用 XmlTextReader 而不是 XDocument。
Could you post the code that you are using to populate the xml variable?
My wild guess is that XDocument is not recognizing the xml fragment as a valid document. I think that XDocument is expecting the
<?xml version="1.0"?>
root node. You might need to use XmlTextReader instead of XDocument.