C# 将 SelectSingleNode 与 XPath 一起使用返回 NULL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17696745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:13:26  来源:igfitidea点击:

Using SelectSingleNode with XPath returns NULL

c#xmlxpathselectsinglenode

提问by Sergey Konkin

I trying to modify an XML file with SelectSingleNode. The structure of file is

我试图用 .xml 文件修改 XML 文件SelectSingleNode。文件的结构是

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ProjectExtensions>
    <Borland.Personality>Delphi.Personality</Borland.Personality>
    <Borland.ProjectType>VCLApplication</Borland.ProjectType>
    <BorlandProject>
      <BorlandProject>
        <Delphi.Personality>
          <Parameters>
            ...
          </Parameters>
          <VersionInfo>
            <VersionInfo Name="IncludeVerInfo">True</VersionInfo>
            <VersionInfo Name="AutoIncBuild">False</VersionInfo>
            <VersionInfo Name="MajorVer">4</VersionInfo>
            <VersionInfo Name="MinorVer">1</VersionInfo>
            <VersionInfo Name="Release">3</VersionInfo>
            <VersionInfo Name="Build">559</VersionInfo>
            <VersionInfo Name="Debug">False</VersionInfo>
            <VersionInfo Name="PreRelease">False</VersionInfo>
            <VersionInfo Name="Special">False</VersionInfo>
            <VersionInfo Name="Private">False</VersionInfo>
            <VersionInfo Name="DLL">False</VersionInfo>
            <VersionInfo Name="Locale">1049</VersionInfo>
            <VersionInfo Name="CodePage">1251</VersionInfo>
          </VersionInfo>
...
...
...

My code on VS C# is

我在 VS C# 上的代码是

using System.Xml;

namespace xmledit
{
    class Program
    {
        private static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("arm.xml");
            var node = doc.SelectSingleNode("//VersionInfo[@Name='Build']");
            if (node != null)
                node.InnerText = "123";                
            doc.Save("temp.xml");
        }
    }
}

So, i trying to modify Tag VersionInfowith Name="Build", but SelectSingleNodereturns NULL. What I doing wrong?

所以,我试图修改标签VersionInfoName="Build",但SelectSingleNode回报率NULL。我做错了什么?

采纳答案by hr_117

Your xml document has an default namespace xmlns="http://schemas.microsoft.com/developer/msbuild/2003"therefore (I assume) you need to use a XmlNamespaceManager.

您的 xml 文档有一个默认命名空间,xmlns="http://schemas.microsoft.com/developer/msbuild/2003"因此(我假设)您需要使用 XmlNamespaceManager。

回答by DotNetDeveloper

You need to define the namespace:

您需要定义命名空间:

Have a look at this answer: SelectSingleNode returning null for known good xml node path using XPath

看看这个答案:SelectSingleNode 使用 XPath 为已知好的 xml 节点路径返回 null

回答by P?l Thingb?

This function will add a namespacemanager to your document. Replace "mysite" with whatever you want. After this, you can select nodes with "mysite:[nodename]".

此函数将向您的文档添加命名空间管理器。用你想要的任何东西替换“mysite”。在此之后,您可以选择带有“mysite:[nodename]”的节点。

public static XmlNamespaceManager AttachNamespaces(ref XmlDocument xmldoc)
    {
        XmlNamespaceManager NS = default(XmlNamespaceManager);
        XmlNode rootnode = default(XmlNode);
        string strTest = null;
        string attrname = null;
        string ns = null;

        NS = new XmlNamespaceManager(xmldoc.NameTable);
        rootnode = xmldoc.DocumentElement;
        strTest = GetAttribute(ref rootnode, "xmlns");
        if (string.IsNullOrEmpty(strTest))
        {
            NS.AddNamespace("mysite", "http://www.mysite.com/");
        }
        else
        {
            NS.AddNamespace("mysite", strTest);
        }

        // Add namespaces from XML root tag
        foreach (XmlAttribute attr in rootnode.Attributes)
        {
            attrname = attr.Name;
            if (attrname.IndexOf("xmlns:") == 0 && !string.IsNullOrEmpty(attrname))
            {
                ns = attrname.Substring(7);
                NS.AddNamespace(ns, attr.Value);
            }
        }

        return NS;

}

Helper function:

辅助功能:

public static string GetAttribute(ref XmlNode mynode, string AttributeName, string DefaultValue = "")
    {
        XmlAttribute myattr = default(XmlAttribute);
        string rtn = "";

        if (mynode != null)
        {
            myattr = mynode.Attributes[AttributeName];
            if (myattr != null)
            {
                rtn = mynode.Attributes[AttributeName].Value;
            }
        }

        if (string.IsNullOrEmpty(rtn))
            rtn = DefaultValue;

        return rtn;
    }

For instance:

例如:

XmlDocument xmldoc = new XmlDocument;
// Load something into xmldoc
XmlNamespaceManager NS = AttachNamespaces(ref XmlDocument xmldoc);
XMLNode mynode = xmldoc.SelectSingleNode("//mysite:VersionInfo[@Name='Build']", NS);

回答by Helmut Hackl

@P?l Thingb?

@P?l Thingb?

You're using the wrong position in your Substring and your solution does not handle a default namespace.

您在 Substring 中使用了错误的位置,并且您的解决方案不处理默认命名空间。

I have modified it, so it works for me now. Thank you! (Although there is still no handling for a "xmlns:" tag without a namespace (attrname==6). I think this should raise an error, because it's not allowed in XML.

我已经修改了它,所以它现在对我有用。谢谢!(虽然仍然没有处理没有命名空间的“xmlns:”标签(attrname==6)。我认为这应该会引发一个错误,因为它在 XML 中是不允许的。

private static XmlNamespaceManager AttachNamespaces(XmlDocument xmldoc)
    {
        XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmldoc.NameTable);
        XmlNode rootnode = xmldoc.DocumentElement;
        string strTest = GetAttribute(ref rootnode, "xmlns");
        nsMgr.AddNamespace("mysite", string.IsNullOrEmpty(strTest) ? "http://example.com/" : strTest);

        // Add namespaces from XML root tag
        if (rootnode.Attributes != null)
            foreach (XmlAttribute attr in rootnode.Attributes)
            {
                string attrname = attr.Name;
                if (attrname.IndexOf("xmlns", StringComparison.Ordinal) == 0 && !string.IsNullOrEmpty(attrname))
                {
                    if (attrname.Length == 5) // default Namespace
                    {
                        string ns = "default";
                        nsMgr.AddNamespace(ns, attr.Value);
                    }
                    else if (attrname.Length > 6)
                    {
                        string ns = attrname.Substring(6);
                        nsMgr.AddNamespace(ns, attr.Value);
                    }
                }
            }

        return nsMgr;

    }