我正在尝试使用XMLDocument
(DItem
>> Title
)解析xml元素
下面是我的代码,但不知怎的,我没有抓住它....任何帮助?
XmlDocument xmldoc = new XmlDocument();
XmlNamespaceManager xmlns = new XmlNamespaceManager(xdoc.NameTable);
xmlns.AddNamespace("DItems", "http://namespace.xsd");
xmldoc.Load(url);
var title = xmldoc.SelectNodes("content", xmlns);
foreach (XmlNode node in title)
{
string title = node.Attributes["Title"].Value;
//this.ddlTitle.Items.Add(new ListItem(title));
}
这是我的XML:
<?xml version='1.0'?>
<root xmlns="http://www.w3.org/2005/Atom">
<title type="text">title</title>
<entry>
<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 title1">
<content:Source Acronym="ABC" OrganizationName="ABC" />
</DItem>
</Item>
</Items>
</content>
</entry>
<entry>
<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 title2">
<content:Source Acronym="ABC" OrganizationName="ABC" />
</DItem>
</Item>
</Items>
</content>
</entry>
<entry>
<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 title3">
<content:Source Acronym="ABC" OrganizationName="ABC" />
</DItem>
</Item>
</Items>
</content>
</entry>
</root>
答案 0 :(得分:0)
var xmldoc = new XmlDocument();
var xmlns = new XmlNamespaceManager(xmldoc.NameTable);
xmlns.AddNamespace("DItems", "http://www.namespace.xsd");
xmldoc.Load(url);
var titleNodes = xmldoc.SelectNodes("//DItems:DItem/@Title", xmlns);
var result = titleNodes.Cast<XmlAttribute>().Select(a => a.Value).ToList();
输出(对象列表):
my title1
my title2
my title3