-1

I am trying to find specific nodes in xml using XDocument. The xml also has a namespace which am importing.

Below is the xml specs

<?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>

I want to retrieve all responses and also only those nodes which have Include nodes present.

I am trying below code to fetch it but I am getting none of the nodes.

XDocument document =  XDocument.Parse(xml);


var name = from nm in document.Elements("responses")
           select nm;

Can anyone let me know how to fix the issue?I need to only fetch the response node.

Thanks in Advance

Kevin
  • 21
  • 3

1 Answers1

1

Try following :

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();
        }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20