首页 > 解决方案 > 使用 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;

谁能告诉我如何解决这个问题?我只需要获取响应节点。

提前致谢

标签: c#xmllinq

解决方案


尝试以下:

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();
        }
    }
}

推荐阅读