开发者

How do you extract a specific element out of an XDocument?

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?


I'm assuming that xml is the XDocument object itself.

An XDocument object contains the root element, not its children. You need to write xml.Root.Element("Prop1");.

EDIT: You also need to include the namespace, like this:

XNamespace ns = "http://schemas.company.com/rah/rah2/2005/";
xml.Root.Element(ns + "Prop1");


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜