Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XNode.DeepEquals unexpectedly returns false

Using XNode.DeepEquals() to compare xml elements, it unexpectedly returns false on two xml documents that I think should be equivalent.

Example

var xmlFromString = XDocument.Parse("<someXml xmlns=\"someNamespace\"/>");
var xmlDirect = new XDocument(new XElement(
  XNamespace.Get("someNamespace") + "someXml"));

Console.WriteLine(xmlFromString.ToString());
Console.WriteLine(xmlDirect.ToString());
Console.WriteLine(XNode.DeepEquals(xmlFromString, xmlDirect));
Console.WriteLine(xmlFromString.ToString() == xmlDirect.ToString());

Output

<someXml xmlns="someNamespace" />
<someXml xmlns="someNamespace" />
False
True

The strings are considered equal, but the XML trees are not. Why?

like image 557
Anders Abel Avatar asked Jun 11 '14 07:06

Anders Abel


1 Answers

I've worked out what the difference is, but not why it's different.

In the first form, you have an xmlns attribute. In the second form, you don't - not in terms of what Attributes() returns. If you explicitly construct an XAttribute, DeepEquals will return true:

var xmlDirect = new XDocument(new XElement(
  XNamespace.Get("someNamespace") + "someXml",
  new XAttribute("xmlns", "someNamespace")));

It's as if the namespace only counts as an attribute when converting the tree to a text representation, basically.

like image 112
Jon Skeet Avatar answered Oct 05 '22 09:10

Jon Skeet