c# - 使用 XDocument 查找特定的 xml 节点
问题描述
我正在尝试使用 XDocument 在 xml 中查找特定节点。xml 还有一个正在导入的命名空间。
以下是xml规格
<?xml version="1.0" encoding="UTF-8"?>
<tns:response xmlns:tns="http://amazon.com/amazonservices">
<tns:responseDirect>
<tns:responseExtract>
<tns:A>ExtractName</tns:A>
</tns:responseExtract>
<tns:responses>
<tns:Name>Response1</tns:Name>
<tns:Include>No</tns:Include>
</tns:responses>
<tns:responses>
<tns:Name>Response2</tns:Name>
<tns:Include>Yes</tns:Include>
</tns:responses>
<tns:responses>
<tns:Name>Response3</tns:Name>
</tns:responses>
</tns:responseDirect>
我想检索所有响应,也只检索那些存在Include节点的节点。
我正在尝试下面的代码来获取它,但我没有得到任何节点。
XDocument document = XDocument.Parse(xml);
var name = from nm in document.Elements("responses")
select nm;
谁能告诉我如何解决这个问题?我只需要获取响应节点。
提前致谢
解决方案
尝试以下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XNamespace ns = doc.Root.GetNamespaceOfPrefix("tns");
var results = doc.Descendants(ns + "responses")
.Where(x => x.Elements(ns + "Include").Any())
.Select(x => new {
include = (string)x.Element(ns + "Include"),
name = (string)x.Element(ns + "Name")
}).ToList();
}
}
}
推荐阅读
- arrays - 如何在 Dart 中将地图添加到列表中
- c# - C# 中有 netstat 命令的替代方法吗?
- python - 没有 pycharm 重新开始
- python - 如何使用 Python 3 在 Jupyter Notebook 中过滤特定数量的行?
- javascript - 当我似乎只发送一个标头时,ExpressJS 抛出多个标头错误
- javascript - 模拟子组件 - 多个组件匹配节点与标记名错误
- asp.net - 在同一个 asp.net Web 应用程序中使用两个 Owin 身份
- python - Python 生成的 lzma 文件缺少未压缩的大小
- php - 在 PHP 中循环 fputcsv 的问题,我该如何解决?
- c++ - 复制“向量”数组:通过 memcpy 还是迭代每个?