Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a NameTable from an XDocument?

How do I get a NameTable from an XDocument?

It doesn't seem to have the NameTable property that XmlDocument has.

EDIT: Judging by the lack of an answer I'm guessing that I may be missing the point.

I am doing XPath queries against an XDocument like this...

document.XPathSelectElements("//xx:Name", namespaceManager); 

It works fine but I have to manually add the namespaces I want to use to the XmlNamespaceManager rather than retrieving the existing nametable from the XDocument like you would with an XmlDocument.

like image 691
Simon Keep Avatar asked Jun 01 '09 11:06

Simon Keep


People also ask

What is XmlNameTable?

Several classes, such as XmlDocument and XmlReader, use the XmlNameTable class internally to store attribute and element names. When an element or attribute name occurs multiple times in an XML document, it is stored only once in the XmlNameTable .

What is namespace manager?

The namespace manager atomizes the strings when they are added by using the AddNamespace method and when a lookup is performed by using the LookupNamespace or LookupPrefix method. The namespace manager implements enumeration support in addition to adding and retrieving namespaces.


2 Answers

You need to shove the XML through an XmlReader and use the XmlReader's NameTable property.

If you already have Xml you are loading into an XDocument then make sure you use an XmlReader to load the XDocument:-

XmlReader reader = new XmlTextReader(someStream); XDocument doc = XDocument.Load(reader); XmlNameTable table = reader.NameTable; 

If you are building Xml from scratch with XDocument you will need to call XDocument's CreateReader method then have something consume the reader. Once the reader has be used (say loading another XDocument but better would be some do nothing sink which just causes the reader to run through the XDocument's contents) you can retrieve the NameTable.

like image 86
AnthonyWJones Avatar answered Sep 30 '22 00:09

AnthonyWJones


I did it like this:

//Get the data into the XDoc XDocument doc = XDocument.Parse(data); //Grab the reader var reader = doc.CreateReader(); //Set the root var root = doc.Root; //Use the reader NameTable var namespaceManager = new XmlNamespaceManager(reader.NameTable); //Add the GeoRSS NS namespaceManager.AddNamespace("georss", "http://www.georss.org/georss");   //Do something with it Debug.WriteLine(root.XPathSelectElement("//georss:point", namespaceManager).Value);   

Matt

like image 45
Matthew McDermott Avatar answered Sep 29 '22 23:09

Matthew McDermott