问题描述:

I have an Xelement which looks like:

<headers batchid="123456" xmlns="http://api.temp.com/ns/">

<header uri="https://api.temp.com/v1.0/headers/147852" id="147852" />

</headers>

I'm trying to read the "uri" attribute. When I tried :

var temp = xmlResponse.Attribute("uri");

it kept return me null.

So I tried:

var temp = xmlResponse.Element("header");

var temp2 = xmlResponse.Element("headers");

and they are also returning null.

What am I doing wrong?

网友答案:

You're ignoring the namespace of the element. Due to the xmlns="...", both the headers and header elements are in a namespace of "http://api.temp.com/ns/". Fortunately, LINQ to XML makes this really easy to fix:

XNamespace ns = "http://api.temp.com/ns/";
var temp = xmlResponse.Element(ns + "headers");
var temp2 = temp.Element(ns + "header");

(Note that the header element is nested within the headers element, hence why I'm calling temp.Element to get at it.)

相关阅读:
Top