c# - Use LINQ XML with a namespace -


i trying find nodes in xml document this:

<?xml version="1.0"?> <trainingcenterdatabase xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:xsd="http://www.w3.org/2001/xmlschema" xmlns="http://www.garmin.com/xmlschemas/trainingcenterdatabase/v2">   <activities>     <activity sport="cyclingtransport">       <id>2014-07-08t15:28:14z</id>     </activity>   </activities> </trainingcenterdatabase> 

i aim extract node value 'id' code this:

xdocument doc = xdocument.load(filepath); list<string> urllist = doc.root.descendants("id")                           .select(x => (string)x)                           .tolist(); console.writeline(urllist.count); 

however count 0, expect 1.

after debugging , editing xml noticed if change trainingcenterdatabase node , remove attributes this:

<trainingcenterdatabase> 

then result count of 1 expected.

so question how take account namespaces can value when trainingcenterdatabase node has these attributes?

namespaces in xml can tricky. i've run problem myself number of times. in likelihood, following fix problem:

xdocument doc = xdocument.load(filepath); list<string> urllist = doc.root.descendants(doc.root.name.namespace.getname("id"))                           .select(x => (string)x)                           .tolist(); console.writeline(urllist.count); 

basically, assumes underlying element have same namespace root element. that's true in case, of course doesn't have be.

the right way, probably, explicitly. now, granted, kind of depends on how you're using , datasource, make decision yourself, require doing more this:

xdocument doc = xdocument.load(filepath); list<string> urllist = doc.root.descendants(system.xml.linq.xname.get("id", "http://www.garmin.com/xmlschemas/trainingcenterdatabase/v2"))                           .select(x => (string)x)                           .tolist(); console.writeline(urllist.count); 

the cause problem default behavior xelement, when not given explicit namespace, assume no namespace. however, default behavior xml spec assume parent's namespace. in case, 2 different, wasn't able find descendant.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -