LINQ xml local search nodes

I am trying to parse an xml file with an XDocument class, with criteria that, if the child node matches the given string, the 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 to use

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 find what is wrong.

Any help is much appreciated! Thank.

+4
source share
3 answers

You ignored the firewall namespace.

Remove the xmlns attribute in XML or try the following:

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
+6
source

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

Querying these objects with Linq will be more direct than what I see in your current implementation.

: SO : XML-

+1

yap, , 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;
+1
source

Source: https://habr.com/ru/post/1692199/


All Articles