【问题标题】:Modifying an XML node with user-provided namespace and node value使用用户提供的命名空间和节点值修改 XML 节点
【发布时间】:2013-03-29 23:11:49
【问题描述】:

花了一段时间,但我终于能够根据用户输入的命名空间和节点名称修改 XML 文档:

string nodeName = "DefinitionName"; // this is really provided by the user
string namespace = "http://schemas.datacontract.org/2004/07/Xxx.Session";  // also user-provided

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(taskResolved.XmlPathAndFileName);
XmlElement rootElement = xmlDocument.DocumentElement;
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDocument.NameTable);
namespaceManager.AddNamespace("snuh", namespace);  // hard-coded prefix, grrr...

XmlNodeList xmlNodes;

xmlNodes = rootElement.SelectNodes("//snuh:" + nodeName, namespaceManager);

我觉得我做错了什么,因为我必须硬编码一个前缀 (snuh)。我可以尝试选择一个前缀,比如 snuh,我希望它永远不会出现在文档中,但这并不是万无一失的。另一种选择是使用 GUID 作为前缀,但这似乎是一种 hack 解决方法。 我错过了什么吗?有没有更好的方法?

XML 文档的顶部如下所示:

<?xml version="1.0" encoding="utf-8"?>
<SessionStateInfo xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="1"
    z:Type="Xxx.SessionStateInfo"
    z:Assembly="Xxx.Common, Version=6.2.0.0, Culture=neutral, PublicKeyToken=null"
    xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/"
    xmlns="http://schemas.datacontract.org/2004/07/Xxx.Session">
      <CoaterNumber>25</CoaterNumber>
      <DefinitionName z:Id="2">TwoLineMarkerDefinition</DefinitionName>
      <EnableManualMode>true</EnableManualMode>

【问题讨论】:

    标签: c# xml


    【解决方案1】:

    如果您只想选择第一个 DefinitionName 节点。

    你可以写

    XmlNode node = rootElement[nodeName, namespace];
    

    如果你想要整个列表:

    XmlNodeList nodeList = rootElement.GetElementsByTagName(nodeName, namespace);
    

    【讨论】:

      【解决方案2】:

      如何使用 XPath local-name()namespace-uri() 函数?

      string xpath = string.Format("//*[local-name()='{0}' and namespace-uri()='{1}']", nodeName, namespace);
      xmlNodes = rootElement.SelectNodes(xpath);
      

      不知道XmlDocument是否支持这些功能,没有测试过。

      【讨论】:

        猜你喜欢
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-20
        • 1970-01-01
        相关资源
        最近更新 更多