How do I parse this xml using Linq to XML?

William Johnston 106 Reputation points
2022-01-13T13:15:01.633+00:00

Hello,

I need assistance on extracting the "Paragraph" elements using Linq to XML from the following XML code:

<?xml version='1.0' encoding='windows-1252' standalone='yes'?>
<Book BookID="-1"
    xmlns="http://xyz.com/Book"
    xmlns:xsi="http://www.w3.org/2001/XmlSchema-instance"
    xsi:schemaLocation="http://xyz.com/Book AIMLXmlSchema.xsd">
    <Paragraph NumberOfSentences='1'>
        <Sentence>A Practical Logic of Cognitive Systems Volume 1
Agenda Relevance A Study in Formal Pragmatics
A Practical Logic of Cognitive Systems Volume 1
Agenda Relevance A Study in Formal Pragmatics
Dov M. Gabbay
Department of Computer Science King&apos;s College London London, UK
and
John Woods
The Abductive Systems Group University of British Columbia Vancouver BC, Canada
2003
ELSEVIER
Amsterdam Boston London New York Oxford Paris San Diego San Francisco Singapore Sydney Tokyo
ELSEVIER SCIENCE B.V.</Sentence>
        <PageInfo>
            <Type>Normal</Type>
            <PageNumber>3</PageNumber>
            <BegIdx>0</BegIdx>
            <EndIdx>489</EndIdx>
            <Location>Not Used</Location>
        </PageInfo>
    </Paragraph>

...

I tried this:

        XElement doc = XElement.Load(strFilepath);

        foreach (var item in doc.Descendants("Paragraph"))
        {
            System.Console.WriteLine("item found.");
        }

but no items were returned.

Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. P a u l 10,761 Reputation points
    2022-01-13T13:31:51.007+00:00

    This is because <Paragraph> is nested under <Book> which has an XML namespace (xmlns) defined, so if you combine that with the tag name to make an XName then it should find the element:

    XNamespace ns = "http://xyz.com/Book";
    XDocument doc = XDocument.Parse(xml);
    XName searchFor = ns + "Paragraph";
    
    foreach (var item in doc.Descendants(searchFor)) {
        Console.WriteLine("item found.");
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.