c# - 如何在 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);
}
}
解决方案
最好使用 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);
}
推荐阅读
- r - 什么算法用于设置交集?
- docker - 无法使用由 Docker Compose 提供的 Drupal 应用程序从 API 获取或发布数据
- r - 在 R 中使用多个参数进行优化
- powerapps - 如何在标签的填充属性中传递替代颜色
- node.js - 节点名称是什么 如果我们添加两个成员 | 亚马逊托管区块链 | REST 服务器
- echarts - 我想使用 echarts 在栏顶部显示蓝色
- html - 是否有可能从 aura 组件刷新 VF 页面?
- sql - 合并选择中的值
- python-3.x - / 'str' 对象的 AttributeError 在 Danjo 中没有属性 'get'
- google-maps - 每次从第二个屏幕回来后颤振刷新谷歌地图