|
Several weeks ago, I needed to query a node in a XML document where a namespace was specified in the the document. Consider the following XML document.
xml
version
="1.0"
encoding
="utf-8"
?>
<
Author
xmlns
:
xsd
="http://www.w3.org/2001/XMLSchema"
xmlns
:
xsi
=
http://www.w3.org/2001/XMLSchema-instance
xmlns
="http://tempuri.org/MyAuthors">
<
ContactInformation
>
<
FirstName
>
John
FirstName
>
<
LastName
>
Doe
LastName
>
<
Address
>
100 Nowhere
Address
>
<
City
>
Gnome
City
>
<
State
>
Alaska
State
>
<
PostalCode
>
PostalCode
>
ContactInformation
>
<
Books
>
<
Title
>
What is your favorite color?
Title
>
<
DatePublished
>
Jan 1, 1886
DatePublished
>
<
NoOfPages
>
16966
NoOfPages
>
Books
>
Author
>
In order to select any the nodes, you would use the following code.
System.Xml.XmlDocument doc =
new
System.Xml.XmlDocument();
doc.Load("c:\authors.xml");
System.Xml.XmlNamespaceManager manager =
new
System.Xml.XmlNamespaceManager(doc.NameTable);
manager.AddNamespace("ns",
http://tempuri.org/MyAuthors
);
string
lastName = doc.SelectSingleNode("/ns:Author/ns:ContactInformation/ns:LastName", manager).InnerText;
It's pretty simple.
See Also:
System.Xml.XmlNamespaceManager Class
System.Xml.XmlDocument
|