Tuesday, June 29, 2010

XDocument or XElement with XmlNamespace

Loading or parsing xml with namspaces are common in development scenarios.When we work with Xdocument and XElement there is no direct way to pass the namespace. Let see how we can work with namspace.

Step1 Create a NameTable

NameTable nameTable = new NameTable();

Step2 Create Namespace Manager
XmlNamespaceManager nameSpaceManager = new XmlNamespaceManager(nameTable );
Step3 Add the Namespace or Ignore It
Adding
nameSpaceManager.AddNamespace("p", "office.server.policy");
Ignoring
nameSpaceManager.AddNamespace("log4net", "urn:ignore");

Step4 Create a ParserContext
XmlParserContext parserContext = new XmlParserContext(null, nameSpaceManager,
null, XmlSpace.None);
Step5 Create a XmlTextReader
XmlTextReader txtReader = new XmlTextReader("Strin XML", XmlNodeType.Element,
parserContext);

Step6 Load the XML
XElement elem = XElement.Load(txtReader);

For Example we have a Log4net xml and we need to parse it

<log4net:event logger="TestingTransmitter.Program"
timestamp="2009-08-02T17:50:18.928+01:00"
level="ERROR"
thread="9"
domain="TestingTransmitter.vshost.exe"
username="domain\user">
<log4net:message>Log entry 103</log4net:message>
<log4net:properties>
<log4net:data name="log4net:HostName" value="machine" />
</log4net:properties>
</log4net:event>


Following code will load the xml without error like "an undeclared namespace"

NameTable nameTable = new NameTable();
XmlNamespaceManager nameSpaceManager
= new XmlNamespaceManager(nameTable );
nameSpaceManager.AddNamespace("log4net", "urn:ignore");
XmlParserContext
parserContext = new XmlParserContext(null, nameSpaceManager,
null,
XmlSpace.None);
XmlTextReader txtReader = new XmlTextReader("Strin XML",
XmlNodeType.Element,
parserContext );
XElement elem =
XElement.Load(txtReader);

No comments:

Post a Comment