2013-09-16 111 views
1

我有以下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> 

我用下面的代碼來獲取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(); 

錯誤:

Object reference not set to an instance of an object. 

但是下面的代碼工作正常,但我想要使用上面的代碼。

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

回答

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

更新:

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

我的XML文件太大,如何將其轉換成字符串「串x」 –

+0

又是怎樣從我答的是差異.. – Anirudha

+0

我問題編輯 –

1

xmlns="urn:hl7-org:v3"是默認的命名空間,所以需要引用...

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

OR

可以避免命名空間本身

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

我的問題編輯 –

1

試試這個

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

如果你想選擇的節點時指定的命名空間,你可以嘗試

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

第一種方法不行 –

+0

我的問題編輯 –

0

正如你正確識別,你需要附加namespace到th e節點查找。

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