Samiey Mehdi
Samiey Mehdi

Reputation: 9424

How to retrieve records from XML element with namespace?

I have the following XML:

<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:hl7-org:v3 CDA_SDTC.xsd" xmlns="urn:hl7-org:v3" xmlns:cda="urn:hl7-org:v3" xmlns:sdtc="urn:hl7-org:sdtc">
<component>
<structuredBody>
  <component>
    <section>
      <templateId root="abs" />
      <title>A1</title>
      <text>
        <paragraph>Hello world!</paragraph>
      </text>
    </section>
  </component>
</structuredBody>
</component>
</Document>

I have the following code used to retrieve paragraph:

XDocument m_xmld = XDocument.Load(Server.MapPath("~/xml/a.xml"));
var m_nodelist = m_xmld.Descendants().Where(p => p.Name.LocalName == "section").
    Select(i => i.Element("text").Element("paragraph").Value).ToList();

Error:

Object reference not set to an instance of an object. 

However the following code works fine, but i want use above code.

XNamespace ns = "urn:hl7-org:v3";
var m_nodelist = m_xmld.Descendants(ns + "section").
       Select(i => i.Element(ns + "text").Element(ns + "paragraph").Value).ToList();

Upvotes: 1

Views: 306

Answers (4)

Damith
Damith

Reputation: 63105

var m_nodelist = m_xmld.Descendants().Where(p => p.Name.LocalName == "rows").
Select(u => u.Attribute("fname").Value).ToList();

update :

var m_nodelist = m_xmld.Descendants().Where(p => p.Name.LocalName == "section").
Select(u => (string)u.Descendants().FirstOrDefault(p => p.Name.LocalName == "paragraph")).ToList();

Upvotes: 1

Kami
Kami

Reputation: 19447

As you correctly identified, you need to append the namespace to the node lookup.

XNamespace nsSys = "urn:hl7-org:v3";
var m_nodelist = m_xmld.Descendants(nsSys + "rows").Select(x => x.Attribute("fname").Value).ToList();

Upvotes: 0

Ovidiu
Ovidiu

Reputation: 1407

Try this

var m_nodelist = m_xmld.Root.Descendants("rows")

If you want to specify a namespace when selecting nodes you can try

var m_nodelist = m_xmld.Root.Descendants(XName.Get("rows", "urn:hl7-org:v3"))

Upvotes: 1

Anirudha
Anirudha

Reputation: 32817

xmlns="urn:hl7-org:v3" is your default namespace and so need to be referenced...

XNamespace ns="urn:hl7-org:v3";
m_xmld.Descendants(ns+"rows")....

OR

you can avoid the namespace itself

m_xmld.Elements().Where(e => e.Name.LocalName == "rows")

Upvotes: 1

Related Questions