我在使用命名空间
解析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);
我习惯做这样的事情,但这不是我认为它应该如何...节点[“href”]为空,无论我似乎改变不能得到
foreach (XmlNode node in includeNodeList)
{
if (node["href"] != null)
{
// Save node["href"].Value here
}
}
如果我在调试器中停止它,我可以看到节点在Outertext中有我想要的信息。 ..我可以保存外部文本并以这种方式解析它,但我知道必须有一些简单的我忽略。有人可以告诉我需要做些什么来获得href值。
答案 0 :(得分:1)
indexer的XmlNode Class返回具有给定名称的第一个子元素,而不是属性的值。
您正在寻找XmlElement.GetAttribute Method:
foreach (XmlElement element in includeNodeList.OfType<XmlElement>())
{
if (!string.IsNullOrEmpty(element.GetAttribute("href")))
{
element.SetAttribute("href", "...");
}
}
或XmlElement.GetAttributeNode Method:
foreach (XmlElement element in includeNodeList.OfType<XmlElement>())
{
XmlAttribute attr = element.GetAttributeNode("href");
if (attr != null)
{
attr.Value = "...";
}
}
答案 1 :(得分:1)
另一种方法是使用XPath选择href
属性:
var includeNodeList = xmlDoc.SelectNodes(@"/root/my:include/@href", nsmgr);
foreach(XmlNode node in includeNodeList)
node.Value = "new value";