繁体   English   中英

通过有效的xpath在XmlDocument.SelectSingleNode上返回空(请尝试旧的答案)

[英]Null return on XmlDocument.SelectSingleNode through valid xpath (did try the old answer)

我已经阅读了另一个问题并将答案应用到我的代码中,但是仍然无法正常工作。
我使用xml读取csproj文件,以在其中读取/写入某些内容。 如果有人关心, 是我的csproject文件!
我的代码:

static void Main(string[] args)
{
    string file = @"D:\Project\svn_longnx\LearnSvnRevision\ConsoleApp1\WindowsFormsApp1\WindowsFormsApp1.csproj";
    XmlDocument xdoc = new XmlDocument();
    xdoc.Load(file);
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(xdoc.NameTable);
    nsmgr.AddNamespace("default", "http://schemas.microsoft.com/developer/msbuild/2003");

    XmlElement root = xdoc.DocumentElement;

    XmlNode node = root.SelectSingleNode("Project/PropertyGroup/ApplicationVersion",nsmgr);

    Console.WriteLine(node.Value);
}

此伪代码失败:

    static void Main(string[] args)
    {
        string file = @"D:\Project\svn_longnx\LearnSvnRevision\ConsoleApp1\WindowsFormsApp1\WindowsFormsApp1.csproj";
        XmlDocument xdoc = new XmlDocument();
        xdoc.Load(file);
        XmlElement root = xdoc.DocumentElement;
        XmlNode node = root.SelectSingleNode("Project/PropertyGroup/ApplicationVersion");
        Console.WriteLine(node.Value);
    }

使用XDocument和关联的对象比旧的XmlDocument位要容易得多。 另外,您可能会因为名称空间而倒下。 相反,请尝试以下代码:

var doc = XDocument.Load(@"D:\Project\svn_longnx\Lear...\WindowsFormsApp1.csproj");
var ns = XNamespace.Get("http://schemas.microsoft.com/developer/msbuild/2003");

var applicationVersionElements = doc.Element(ns + "Project")
    .Descendants(ns + "PropertyGroup")
    .Descendants(ns + "ApplicationVersion");

foreach (var element in applicationVersionElements)
{
    Console.WriteLine(element.Name);
}

这只是作为获取特定元素以演示其易用性示例的一种方式。

注意,您可能需要using System.Xml.Linq;添加using System.Xml.Linq;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM