Displaying Indented xml  
Author Message
Marshes





PostPosted: XML and the .NET Framework, Displaying Indented xml Top

Hi all, I am trying to write an xml file from the DOM to a text box, in its proper format (indented). I am migrating from visual basic 6.0 and have the function I could make suitable for visual studio 2005 but was wondering if there is any thing clever built in with visual studio to do this. I have came across some things like the XmlTextWriter which indents etc but this doesnt really suit my needs (or at least I cant get it to!!)

Here is the vb 6.0 function so u get the idea of what I want to do.

Function transformIndentXML(xmldoc As MSXML2.IXMLDOMNode, indent As Integer) As String

Dim nodeList As MSXML2.IXMLDOMNodeList
Dim subNode As MSXML2.IXMLDOMNode

Dim idx As Integer
Dim indentStr As String

indentStr = Space(indent * 3)

Set nodeList = xmldoc.childNodes
If Not nodeList Is Nothing Then
For idx = 0 To nodeList.length - 1
Set subNode = nodeList.Item(idx)
If Not subNode.nodeType = NODE_TEXT Then
If subNode.hasChildNodes Then
transformIndentXML = transformIndentXML + vbCrLf + indentStr + "<" + subNode.nodeName + ">"
If subNode.childNodes.Item(0).nodeType = NODE_TEXT Then
transformIndentXML = transformIndentXML + subNode.childNodes.Item(0).Text + "</" + subNode.nodeName + ">"
Else
transformIndentXML = transformIndentXML + transformIndentXML(subNode, indent + 1)
transformIndentXML = transformIndentXML + vbCrLf + indentStr + "</" + subNode.nodeName + ">"
End If
Else
transformIndentXML = transformIndentXML + vbCrLf + indentStr + "<" + subNode.nodeName + "/>"
End If
End If

Next idx
End If


Any help would be appreciated.
Thanks, bailey.


.NET Development13  
 
 
Oleg Tkachenko





PostPosted: XML and the .NET Framework, Displaying Indented xml Top

What's wrong with XmlWriter It can wormat XML just fine:

XmlDocument doc = new XmlDocument();
doc.Load("../../source.xml");
StringWriter sw = new StringWriter();
XmlWriterSettings s = new XmlWriterSettings();
s.Indent = true;
XmlWriter w = XmlWriter.Create(sw, s);
doc.Save(w);
w.Close();
String xml = sw.ToString();
Console.WriteLine(xml);


 
 
Marshes





PostPosted: XML and the .NET Framework, Displaying Indented xml Top

Hey thanks Oleg that works brilliantly. Still trying to get my head round the migration but I can see so many benifits. I quess I'm behind the game a bit, I got as far as the XmlWriter but didnt realise you can save your xml doc straight to it, very handy.

Any way thanks again, bailey.