using XElement to query for a node in namespace(使用 XElement 查询命名空间中的节点)
问题描述
我正在尝试从看起来像这样的 csproj 文件中提取一个节点,但无法让它工作 - 大概是因为命名空间声明.
i'm trying to pull out a node from a csproj file that looks like this, but can't get it to work - presumably because of the namespace declaration.
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
<PropertyGroup>
<RegisterForComInterop>true</RegisterForComInterop>
这失败得很惨:
XDocument cpo = XDocument.Load(file);
XmlNamespaceManager nsm = new XmlNamespaceManager(new NameTable());
nsm.AddNamespace("x", "http://schemas.microsoft.com/developer/msbuild/200");
IEnumerable<XElement> list3 = cpo.XPathSelectElements("//x:RegisterForComInterop[.='true']", nsm);
请问大家有什么想法吗?
Anyone any ideas please?
谢谢.
推荐答案
你真的要为此使用 XPath 吗?在 LINQ to XML 中使用命名空间真的很容易:
Do you really want to use XPath for this? It's really easy to use namespaces within LINQ to XML:
XDocument cpo = XDocument.Load(file);
XNamespace x = "http://schemas.microsoft.com/developer/msbuild/2003";
var elements = cpo.Descendants(x + "RegisterForComInterop")
.Where(x => (string) x == "true");
或者,如果您绝对确信每个 RegisterForComInterop 都将具有适当的布尔值,您可以使用 explicitXElement 到 bool 转换:
or if you're absolutely convinced that every RegisterForComInterop will have an appropriate Boolean value you can use the explicit XElement to bool conversion:
XDocument cpo = XDocument.Load(file);
XNamespace x = "http://schemas.microsoft.com/developer/msbuild/2003";
var elements = cpo.Descendants(x + "RegisterForComInterop")
.Where(x => (bool) x);
如果涉及命名空间,我个人通常会选择这条路线而不是 XPath尤其是.
Personally I would usually go this route rather than XPath especially if namespaces are involved.
这篇关于使用 XElement 查询命名空间中的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 XElement 查询命名空间中的节点
基础教程推荐
- Moq It.Is<>不匹配 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
