0

I would like to parse the below xml using XDocument in Linq.

<?xml version="1.0" encoding="UTF-8"?>
<string xmlns="http://tempuri.org/">
   <Sources>
      <Item>
         <Id>1</Id>
         <Name>John</Name>
      </Item>
      <Item>
         <Id>2</Id>
         <Name>Max</Name>
      </Item>
      <Item>
         <Id>3</Id>
         <Name>Ricky</Name>
      </Item>
   </Sources>
</string>

My parsing code is :

    var xDoc = XDocument.Parse(xmlString);
    var xElements = xDoc.Element("Sources")?.Elements("Item");
    if (xElements != null)
        foreach (var source in xElements)
        {
            Console.Write(source);
        }

xElements is always null. I tried using namespace as well, it did not work. How can I resolve this issue?

2 Answers 2

1

Try below code:

string stringXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><string xmlns=\"http://tempuri.org/\"><Sources><Item><Id>1</Id><Name>John</Name></Item><Item><Id>2</Id><Name>Max</Name></Item><Item><Id>3</Id><Name>Ricky</Name></Item></Sources></string>";
XDocument xDoc = XDocument.Parse(stringXml);
var items = xDoc.Descendants("{http://tempuri.org/}Sources")?.Descendants("{http://tempuri.org/}Item").ToList();

I tested it and it correctly shows that items has 3 lements :) Maybe you used namespaces differently (it's enough to inspect xDoc objct in object browser and see its namespace).

Sign up to request clarification or add additional context in comments.

Comments

1

You need to concatenate the namespace and can directly use Descendants method to fetch all Item nodes like:

XNamespace ns ="http://tempuri.org/";
var xDoc = XDocument.Parse(xmlString);
var xElements = xDoc.Descendants(ns + "Item");

 foreach (var source in xElements)
 {
     Console.Write(source);
 }

This prints on Console:

<Item xmlns="http://tempuri.org/">
  <Id>1</Id>
  <Name>John</Name>
</Item><Item xmlns="http://tempuri.org/">
  <Id>2</Id>
  <Name>Max</Name>
</Item><Item xmlns="http://tempuri.org/">
  <Id>3</Id>
  <Name>Ricky</Name>
</Item>

See the working DEMO Fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.