2011-09-19 133 views
0

我想解析一個xml元素(DItem >>Title) 下面是我的代碼,但不知何故,我沒有得到它....任何幫助嗎?解析XML元素

XDocument xdoc1 = XDocument.Load(url); 
XNamespace ns = "http://sitename/items.xsd"; 
string topic = xdoc1.Descendants(ns + "DItem") 
      .Select(x => (string)x.Attribute("Title")) 
      .FirstOrDefault(); 

<?xml version='1.0'?> 
<root xmlns="http://www.w3.org/2005/Atom"> 
    <title type="text">title</title> 
    <entry> 
    <id>da7d3189-fd89-4d3f-901c-30eab7a3baa5</id> 
    <title type="text">Swimming Pools</title> 
    <summary type="text"></summary> 
    <updated>2011-08-19T19:02:21Z</updated> 
    <link rel="alternate" href="link" /> 
    <link href="link" /> 
    <content type="application/xml"> 
     <Items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.namespace.xsd"> 
     <CatalogSource Acronym="ABC" OrganizationName="organization name" /> 
     <Item Id="28466" CatalogUrl="url"> 
      <DItem xmlns:content="http://namespace.xsd" TargetUrl="http://index.html" Title="my title"> 
      <content:Source Acronym="ABC" OrganizationName="ABC" /> 
      </DItem> 
     </Item> 
     </Items> 
    </content> 
    </entry> 
</root> 

回答

0

使用命名空間的 「http://www.namespace.xsd」 應該(和不)工作:

XNamespace ns = "http://www.namespace.xsd"; 
string topic = xdoc1.Descendants(ns + "DItem") 
        .Select(x => (string)x.Attribute("Title")) 
        .FirstOrDefault(); 

由於DItem是沒有資格與命名空間本身,它會使用默認在其父元素上指定爲xmlns="http://www.namespace.xsd"的名稱空間。

+0

嗯,不知道什麼是錯的,它返回'null' ...如果你看我的xml我也有'

+0

如果你想'DItem'在內容命名空間中,你必須在其祖先之一聲明xmlns:content,並且名字是'content:DItem' – BrokenGlass

+0

我迷失在這裏了...上面的xml是我從第三方供應商,我不控制...所以我有興趣只提取'標題'。那麼爲了提取標題而不修改xml結構的方式,我需要做什麼? –