C# 使用XMLDocument提取XML属性
我正在尝试使用C# 使用XMLDocument提取XML属性,c#,.net,xml,xpath,C#,.net,Xml,Xpath,我正在尝试使用XMLDocument(DItem>Title)解析xml元素 下面是我的代码,但不知何故我没有得到它。。。。有什么帮助吗 XmlDocument xmldoc = new XmlDocument(); XmlNamespaceManager xmlns = new XmlNamespaceManager(xdoc.NameTable); xmlns.AddNamespace("DItems", "http://namespace.x
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>
标题
尝试执行xmldoc。选择SingleNode(“标题”);您所做的是在“content\”xml树内搜索,但标题在该树外。@Roy:1+-谢谢,外部情况如何,我有内容>>>数据项>>>在数据项内我有标题-正确吗?抱歉,我没有注意到该标题,我假设它是外部的。我之所以在中使用for loop
是因为我正在将结果添加到dropdownlist中,如代码所示…@Abu,那么问题出在哪里?为示例XML提供多个元素sokay,因此我尝试像这样循环foreach(结果中的XmlNode节点){string title=node.Attributes[“title”].Value;}但我遇到了错误无法将字符串转换为xmlnode@Abu,foreach(结果中的字符串标题){//title的类型为string}
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