October 5, 2005

Using XmlTextReader With a String

Pattern for Using XmlTextReader with a string. This is useful for testing your Xml Parsing

//Create the XML fragment to be parsed.
string xmlFrag =
  "<Transport Label=\"TS1\" TransportId=\"1\" 
OrigNetworkId=\"1\" >" + " <Metadata>" + " <Id>c98dced0-1efc-48c3-aa37-cae5141c6615</Id>" + " <ProfileDescription>Test TS</ProfileDescription>" + " </Metadata>" + "</Transport>"; // Create a XmlTextReader that will read from an Xml string XmlTextReader xmlReader = new XmlTextReader( xmlFrag, XmlNodeType.Element, new XmlParserContext(null, new XmlNamespaceManager(
new NameTable()), null, XmlSpace.Default)); // <= XXX // Can set how to handle whitespace here! //xmlReader.WhitespaceHandling = WhitespaceHandling.All; Transport transport = XmlProcessor.ReadTransport(xmlReader) ; //Close the reader. xmlReader.Close();

A longer version for the creating the XmlTextReader. Replace the line XXX with this

//Create the XmlNamespaceManager.
NameTable nt = new NameTable();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
//Create the XmlParserContext.
XmlParserContext context = new XmlParserContext(
null, nsmgr, null, XmlSpace.Default); //Create the reader, tell it the fragment represents
an Xml Element type of node XmlTextReader xmlReader = new XmlTextReader(
xmlFrag, XmlNodeType.Element, context);

No comments: