简体   繁体   English

如何从带有命名空间的XML元素中检索记录?

[英]How to retrieve records from XML element with namespace?

I have the following XML: 我有以下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 : 我有以下代码用于检索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();

xmlns="urn:hl7-org:v3" is your default namespace and so need to be referenced... xmlns="urn:hl7-org:v3"是您的默认名称空间,因此需要引用...

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")

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"))
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();

As you correctly identified, you need to append the namespace to the node lookup. 正确识别后,需要将namespace附加到节点查找。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM