read or convert xml file to a string

J

Jon Paal

how can I read an xml file and convert it to a string

or

convert an XmlTextReader to a string
 
K

KJ

Hi Jon,

The C# code below shows you how to do the latter.

It assumes that you have a boolean variable called IsFragment which
indicates the kind of Xml you are dealing with (either a well-formed
document or just a fragment), because these are read out differently.
You can use this example to get the content of your XmlReader into a
string:

XmlReader reader = o.ExecuteXmlReader(); //uses a SqlCommand to get an
XmlReader, for example, from SQL Server. You can also use the
constructor of the XmlTextReader
StringBuilder XmlStringB = new StringBuilder();
if (!IsFragment)
{
reader.MoveToContent();
XmlStringB.Append(reader.ReadOuterXml());
}
else
{
while (reader.Read())
{
XmlStringB.Append(reader.ReadOuterXml());
}
}
return XmlStringB.ToString()

-Hope this helps.
 
D

David Veeneman

Since an XML file is just a text file, couldn't you just use a text reader,
instead of an XML reader, to read the file?
 
J

Jon Paal

need a little more help getting this into vb (IsFragment ?)


Dim XmlStringB As New StringBuilder()

Dim reader as New DataSet()
reader.ReadXml(Server.MapPath("project.xml"))

If Not IsFragment Then
reader.MoveToContent()
XmlStringB.Append(reader.ReadOuterXml())
Else
While reader.Read()
XmlStringB.Append(reader.ReadOuterXml())
End While
End If
Return XmlStringB.ToString()
 
K

KJ

Hi Jon,

The IsFragment is just a boolean type variable is declare in my code.
Basically, I use it because of the way the Xml is read in the if/else
that follows. So, if you know your Xml is always well-formed, just do:

Dim IsFragment as Boolean = True

before the if/else, and you are all set.
 
J

Jon Paal

reader.MoveToContent() is throwing an error


Compiler Error Message: BC30456: 'MoveToContent' is not a member of 'System.Data.DataSet'.

Source Error:


Line 93:
Line 94: If Not IsFragment Then
Line 95: reader.MoveToContent()
Line 96: XmlStringB.Append(reader.ReadOuterXml())
Line 97: Else
 
K

KJ

OK. Earlier you wrote that you want to read from an XmlTextReader, not
a DataSet. What happened to that idea?
 
J

Jon Paal

I have this working:

Dim fp As StreamReader
Dim xmlData As String

fp = File.OpenText(Server.MapPath("project.xml"))
xmlData = fp.ReadToEnd()
fp.Close()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top