SwiftedMind
SwiftedMind

Reputation: 4287

Can't get the children of root element in xml file

I have an xml file, structured like this:

<textureatlas xmlns="http://www.w3.org/1999/xhtml" imagepath="someImage.png">
  <subtexture name="1" x="342" y="0" width="173" height="171"></subtexture>
  <subtexture name="2" x="0" y="346" width="169" height="173"></subtexture>
  <subtexture name="3" x="0" y="173" width="169" height="173"></subtexture>
  <subtexture name="4" x="0" y="0" width="169" height="173"></subtexture>
  <subtexture name="5" x="342" y="171" width="169" height="173"></subtexture>
  <subtexture name="6" x="169" y="0" width="173" height="171"></subtexture>
  <subtexture name="7" x="169" y="173" width="173" height="171"></subtexture>
  <subtexture name="8" x="169" y="346" width="173" height="171"></subtexture>
  <subtexture name="9" x="342" y="346" width="173" height="171"></subtexture>
</textureatlas>

And I want to iterate through every subtexture element, using Linq in C#. However, my code doesn't work:

var document = XDocument.Load(pathToXml);
var root = document.Root;

if (root == null)
{
    throw new Exception();
}

var subtextureElements =
    from element in root.Elements("subtexture")
    select element;

foreach (var element in subtextureElements)
{
    Debug.WriteLine("okay");
}

The Debugger doesn't print anything. And when I add a breakpoint, I see that subtextureElements is empty. What am I doing wrong? I searched the internet and the approach with root.Elements("subtextures) isn't working either.

Upvotes: 4

Views: 417

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499770

This call

root.Elements("subtexture")

asks for elements called subtexture with no namespace. Due to namespace defaulting with the xmlns=... attribute, they're actually in the namespace with the URI http://www.w3.org/1999/xhtml. Fortunately LINQ to XML makes it really easy to use namespaces, using the implicit conversion from string to XNamespace, and then the + operator to combine a namespace with an element name to create an XName:

XNamespace ns = "http://www.w3.org/1999/xhtml";
var subtextureElements = root.Elements(ns + "subtexture");

(There's no benefit in using a query expression here, by way. I suspect XDocument.Root will never be null for a document loaded with XDocument.Load, either.)

Upvotes: 5

Related Questions