【问题标题】:c# parse xml with a namespacec# 使用命名空间解析 xml
【发布时间】:2011-09-20 00:06:10
【问题描述】:

我在解析带有命名空间的 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                    
  }
}

如果我在调试器中停止它,我可以看到节点在 Outertext 中有我想要的信息。 ..我可以保存外部文本并以这种方式解析它,但我知道必须有一些简单的东西我忽略了。谁能告诉我我需要做什么才能获得href值。

【问题讨论】:

  • 你能发布更多的 XML,比如声明 xmlns 的地方吗?
  • 你能显示源 XML 吗?使用根和命名空间定义。

标签: c# parsing namespaces xmldocument


【解决方案1】:

XmlNode Classindexer 返回具有给定名称的第一个子元素,而不是属性的值。

您正在寻找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 = "...";
    }
}

【讨论】:

  • 语法对于 c# 来说有点过时。不需要 .OfType() 和 GetAttributeNode 返回一个字符串.. 但这确实让我走上了正确的道路,感谢您的帮助
【解决方案2】:

另一种方法是仅使用 XPath 选择 href 属性:

var includeNodeList = xmlDoc.SelectNodes(@"/root/my:include/@href", nsmgr);
foreach(XmlNode node in includeNodeList)
    node.Value = "new value";

【讨论】:

    猜你喜欢
    • 2012-10-14
    • 2021-05-03
    • 2014-01-10
    • 2010-11-08
    • 2018-07-15
    • 2012-06-11
    • 2015-09-08
    相关资源
    最近更新 更多