问题描述
|
我在解析带有名称空间的xml文件时遇到了一些麻烦
xml文件中有这样一行
<my:include href=\"include/myfile.xml\"/>
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(file);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace(\"my\",\"http://www.w3.org/2001/xinclude\");
XmlNodeList includeNodeList = xmlDoc.SelectNodes(@\"/root/my:include\",nsmgr);
我已经习惯做这样的事情,但是这并没有读到我的想法。node[\“ href \”]为空,无论我似乎改变了什么
foreach (XmlNode node in includeNodeList)
{
if (node[\"href\"] != null)
{
// Save node[\"href\"].Value here
}
}
如果我在调试器中将其停止,则可以在外部文本中看到节点具有我想要的信息。 ..我可以保存外部文本并以这种方式进行解析,但是我知道必须忽略一些简单的内容。有人可以告诉我我需要做什么来获得href的价值。
解决方法
XmlNode类的索引器返回具有给定名称而不是属性值的第一个子元素。
您正在寻找XmlElement.GetAttribute方法:
foreach (XmlElement element in includeNodeList.OfType<XmlElement>())
{
if (!string.IsNullOrEmpty(element.GetAttribute(\"href\")))
{
element.SetAttribute(\"href\",\"...\");
}
}
或XmlElement.GetAttributeNode方法:
foreach (XmlElement element in includeNodeList.OfType<XmlElement>())
{
XmlAttribute attr = element.GetAttributeNode(\"href\");
if (attr != null)
{
attr.Value = \"...\";
}
}
, 另一种方法是使用XPath选择href
属性:
var includeNodeList = xmlDoc.SelectNodes(@\"/root/my:include/@href\",nsmgr);
foreach(XmlNode node in includeNodeList)
node.Value = \"new value\";