4

I try to parse an xml file with XDocument class, with criteria that if the child node matches a given string, its parent node is selected.

<SalesQuotes xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://api.some.com/version/1">
  <Pagination>
    <NumberOfItems>2380</NumberOfItems>
    <PageSize>200</PageSize>
    <PageNumber>1</PageNumber>
    <NumberOfPages>12</NumberOfPages>
  </Pagination>
  <SalesQuote>
    <Guid>825634b9-28f5-4aa7-98e7-5e4a4ed6bc6a</Guid>
    <LastModifiedOn>2018-01-09T12:23:56.6133445</LastModifiedOn>
    <Comments>Please note:
installation is not included in this quote
    </Comments>
  </SalesQuote>
</SalesQuotes>

I tried using

var contents = File.ReadAllText(path: "test1.xml");
var doc = XDocument.Parse(contents);
var root = doc.Root;
var sq = root.Elements("SalesQuote");//return null

var theQuote = root.Elements("SalesQuote").Where(el => el.Element("Guid").Value == "825634b9-28f5-4aa7-98e7-5e4a4ed6bc6a");//return null

var theAlternativeQuote =
            from el in doc.Descendants("SalesQuote").Elements("Guid")
            where el.Value == "825634b9-28f5-4aa7-98e7-5e4a4ed6bc6a"
            select el;//return null

I can't seem to find what's wrong.

Any help is much appreciated! Thanks.

Isaac L
  • 101
  • 1
  • 7

3 Answers3

6

You ignored the namespace bro.

Do remove the xmlns attribute in your XML or try this:

var contents = File.ReadAllText("XMLFile1.xml");
var doc = XDocument.Parse(contents);
var root = doc.Root;
XNamespace ns = "http://api.some.com/version/1";
var sq = root.Descendants(ns + "SalesQuotes"); //return null

var theQuote = root.Elements(ns + "SalesQuote")
    .Where(el => el.Element(ns + "Guid").Value == "825634b9-28f5-4aa7-98e7-5e4a4ed6bc6a"); //return null

var theAlternativeQuote =
    from el in doc.Descendants(ns + "SalesQuote").Elements(ns + "Guid")
    where el.Value == "825634b9-28f5-4aa7-98e7-5e4a4ed6bc6a"
    select el; //return null
Ferhat Sayan
  • 216
  • 1
  • 4
  • 19
1

If you are not too concerned about keeping your current implementation, you could consider using a Typed DataSet and load your XML into fully typed, structured objects.

Querying those objects with Linq will be more straight forward than what I see in your current implementation.

You might also find this useful: SO Question: Deserialize XML Document to Objects

Ian Robertson
  • 2,652
  • 3
  • 28
  • 36
1

yap, you're missing the namespace that you can grab with document.Root.GetDefaultNamespace()

    // Load
    var document = XDocument.Parse(xml);
    var xmlns = document.Root.GetDefaultNamespace();

    // Find
    var query = from element in document
                    .Descendants(xmlns + "SalesQuote")
                    .Elements(xmlns + "Guid")
                where element.Value == "825634b9-28f5-4aa7-98e7-5e4a4ed6bc6a"
                select element;
Dan Dohotaru
  • 2,809
  • 19
  • 15