2011-09-19 193 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结构的方式,我需要做什么? –