首页 > 解决方案 > 如何在 C# 中使用 XPath 包含

问题描述

我正在努力使用 XPATH 中的 contains(text,'some text') 。

我看到了这个链接How to use XPath contains()但由于某种原因对我不起作用

我需要删除项目引用,因此我只想使用“ProjectName”进行选择(不指定完整路径)我从这个答案中获取了一个脚本如何使用 Powershell 添加/删除对 csproj 的引用?(参见 RemoveReference.ps1)

这是我的代码,还有一个小提琴https://dotnetfiddle.net/Cq5fa6

using System;
using System.Xml;
                    
public class Program
{
    public static void Main()
    {
            //Declare the XML Document here
            XmlDocument Doc = new XmlDocument();

            //Load you xml here
            //Doc.LoadXml(TransportResponse.Response)
            Doc.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>
<Project ToolsVersion=""15.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
  <ItemGroup>
    <ProjectReference Include=""..\ProjectReferencesToolkit.Core\ProjectReferencesToolkit.Core.csproj"">
      <Project>{6c167ddd-7ce8-4087-9f8c-6986145b97d1}</Project>
      <Name>ProjectReferencesToolkit.Core</Name>
    </ProjectReference>
  </ItemGroup>
  <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" />
</Project>
");

//I need to use contains here to only search for ProjectReferencesToolkit.Core.csproj (not specifying full path)
var XPath = String.Format("//a:ProjectReference[@Include='{0}']","..\\ProjectReferencesToolkit.Core\\ProjectReferencesToolkit.Core.csproj");    
    var nsmgr = new XmlNamespaceManager(Doc.NameTable);
    nsmgr.AddNamespace("a","http://schemas.microsoft.com/developer/msbuild/2003");
    var node = Doc.SelectSingleNode(XPath, nsmgr);
        
Console.WriteLine(node.InnerXml);
        
    }
}

标签: c#xmlxpath

解决方案


最好使用 LINQ to XML API。自 2007 年以来,它在 .Net Framework 中可用。

C#

void Main()
{
    XDocument xsdoc = XDocument.Parse(@"<?xml version='1.0' encoding='utf-8'?>
        <Project ToolsVersion='15.0'
                 xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
            <ItemGroup>
                <ProjectReference Include='..\ProjectReferencesToolkit.Core\ProjectReferencesToolkit.Core.csproj'>
                    <Project>{6c167ddd-7ce8-4087-9f8c-6986145b97d1}</Project>
                    <Name>ProjectReferencesToolkit.Core</Name>
                </ProjectReference>
            </ItemGroup>
            <Import Project='$(MSBuildToolsPath)\Microsoft.CSharp.targets'/>
        </Project>");
        
        string SearchFor = @"ProjectReferencesToolkit.Core.csproj";
        
        XNamespace ns = xsdoc.Root.GetDefaultNamespace();
        XElement xelem = xsdoc.Descendants(ns + "ProjectReference")
            .FirstOrDefault(x => x.Attribute("Include").Value.EndsWith(SearchFor));
        
        Console.WriteLine(xelem);
}

推荐阅读