c#使用名称空间解析xml

问题描述

| 我在解析带有名称空间的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\";
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...