473,485 Members | 1,393 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Easiest way to generate XML in VB.NET

Quick (hopefully easy) question for you guys.
What is going to be the quickest/easiest way to generate XML from VB.NET?
Note: I don't mean an XML file, but XML in memory somehow (an XML-related
object, but one that would have a method for getting the fully-formed XML
back out again).
For example, what will be my easiest way to build the following in memory:

<CommandXML>
<cmd name="1" action="2">
<arg name="3" value = "4"/>
<arg name="5" value = "6"/>
</cmd>
<cmd name="7" action="9">
<arg name="9" value = "0"/>
</cmd>
</CommandXML>

Basically, the reason I need this in memory, is I need to build this XML,
then send it (as a string) to a server component.
Thanks!
-Scott
Nov 12 '05 #1
7 10561
You'll be delightfully surprised how easy it is. You basically use the
XMLserialization object to create an object or series of nested objects
that can read in or write out XML to a text file or other output
source.

The WROX Visual Basic for Beginners book cover this in detail.

Nov 12 '05 #2
Scott,
As Bingomanatee suggests XML Serialization is one of the easier ways,
especially if you can represent your data as Objects. The trick is getting
the "arrays" correct (the list of commands & the list of arguments).

Something like (note the sample only supports a single cmd & a single arg):

Imports System.Xml.Serialization

Dim writer As New System.Xml.XmlTextWriter("CommandXml.xml",
System.Text.Encoding.UTF8)
writer.Formatting = Xml.Formatting.Indented
writer.Indentation = 1
writer.IndentChar = ControlChars.Tab

Dim serializer As New
System.Xml.Serialization.XmlSerializer(GetType(Com mandXml))

Dim command As New CommandXml
command.Command = New command
command.Command.Name = "1"
command.Command.Action = "2"
command.Command.Argument = New Argument
command.Command.Argument.Name = "3"
command.Command.Argument.Value = "4"

serializer.Serialize(writer, command)
writer.Close()
Public Class CommandXml

Private m_command As Command

<XmlElement("cmd")> _
Public Property Command() As Command
Get
Return m_command
End Get
Set(ByVal value As Command)
m_command = value
End Set
End Property

End Class

Public Class Command

Private m_name As String
Private m_action As String
Private m_argument As Argument

<XmlAttributeAttribute("name")> _
Public Property Name() As String
Get
Return m_name
End Get
Set(ByVal value As String)
m_name = value
End Set
End Property

<XmlAttributeAttribute("action")> _
Public Property Action() As String
Get
Return m_action
End Get
Set(ByVal value As String)
m_action = value
End Set
End Property

<XmlElement("arg")> _
Public Property Argument() As Argument
Get
Return m_argument
End Get
Set(ByVal value As Argument)
m_argument = value
End Set
End Property

End Class

Public Class Argument

Private m_name As String
Private m_value As String

<XmlAttributeAttribute("name")> _
Public Property Name() As String
Get
Return m_name
End Get
Set(ByVal value As String)
m_name = value
End Set
End Property

<XmlAttributeAttribute("value")> _
Public Property Value() As String
Get
Return m_value
End Get
Set(ByVal value As String)
m_value = value
End Set
End Property

End Class

I find using System.Text.XmlTextWriter to be equally easy. Something like:

Dim writer As New System.Xml.XmlTextWriter("CommandXml.xml",
System.Text.Encoding.UTF8)
writer.Formatting = Xml.Formatting.Indented
writer.Indentation = 1
writer.IndentChar = ControlChars.Tab
writer.WriteStartDocument()

' <CommandXML>
writer.WriteStartElement("CommandXML")

' <cmd name="1" action="2">
writer.WriteStartElement("cmd")
writer.WriteAttributeString("name", "1")
writer.WriteAttributeString("action", "2")

' <arg name="3" value = "4"/>
writer.WriteStartElement("arg")
writer.WriteAttributeString("name", "3")
writer.WriteAttributeString("value", "4")
writer.WriteEndElement() ' arg

' <arg name="5" value = "6"/>
writer.WriteStartElement("arg")
writer.WriteAttributeString("name", "5")
writer.WriteAttributeString("value", "6")
writer.WriteEndElement() ' arg

' </cmd>
writer.WriteEndElement() ' cmd

' <cmd name="7" action="9">
writer.WriteStartElement("cmd")
writer.WriteAttributeString("name", "7")
writer.WriteAttributeString("action", "9")

' <arg name="9" value = "0"/>
writer.WriteStartElement("arg")
writer.WriteAttributeString("name", "9")
writer.WriteAttributeString("value", "0")
writer.WriteEndElement() ' arg

' </cmd>
writer.WriteEndElement() ' cmd

' </CommandXML>
writer.WriteEndElement() ' CommandXML

writer.WriteEndDocument()
writer.Close()

Hope this helps
Jay

"Scott M. Lyon" <sc******************@rapistan.BLUE.com> wrote in message
news:OI**************@TK2MSFTNGP09.phx.gbl...
| Quick (hopefully easy) question for you guys.
|
|
| What is going to be the quickest/easiest way to generate XML from VB.NET?
|
|
| Note: I don't mean an XML file, but XML in memory somehow (an XML-related
| object, but one that would have a method for getting the fully-formed XML
| back out again).
|
|
| For example, what will be my easiest way to build the following in memory:
|
| <CommandXML>
| <cmd name="1" action="2">
| <arg name="3" value = "4"/>
| <arg name="5" value = "6"/>
| </cmd>
| <cmd name="7" action="9">
| <arg name="9" value = "0"/>
| </cmd>
| </CommandXML>
|
|
|
| Basically, the reason I need this in memory, is I need to build this XML,
| then send it (as a string) to a server component.
|
|
| Thanks!
| -Scott
|
|
Nov 12 '05 #3
Hello Scott,

Well, may be I'm simplistic, but if you just want to send a string to a
server, then build the string:

StringBuilder xml=new StringBuilder();
xml.Append("<CommandXML>\n");
xml.Append(" <cmd name=\"1\" action=\"2\">\n");
xml.Append(" <arg name=\"3\" value=\"4\"/>\n");
xml.Append(" <arg name=\"5\" value=\"6\"/>\n");
xml.Append(" </cmd>\n");
xml.Append(" <cmd name=\"7\" action=\"9\">\n");
xml.Append(" <arg name=\"9\" value=\"0\"/>\n");
xml.Append(" </cmd>\n");
xml.Append("</CommandXML>");

Then, when you want to access the string you do a
xml.ToString();

And, if you want to check the Xml you do a:
try {
XmlDocument doc=new XmlDocument();
doc.LoadXml(xml.ToString());
} catch (XmlException e) {
throw new Exception("Error "+e.Message+" in line "+e.LineNumber+"
at\n"+xml.ToString());
}

Hope this helps,
jmgonet
Nov 12 '05 #4
jmgonet wrote:
Well, may be I'm simplistic, but if you just want to send a string to a
server, then build the string:
Bad idea. Then you must take care of XML syntax issues - well-formdness,
escaping special characters, encoding issues etc etc etc. It's always
much better to let XML API to deal with XML.
StringBuilder xml=new StringBuilder();
xml.Append("<CommandXML>\n");


That's a code from 1998. In 2005 you can have a luxury to use XmlTextWriter.

--
Oleg Tkachenko [XML MVP, MCP]
http://blog.tkachenko.com
Nov 12 '05 #5
> That's a code from 1998. In 2005 you can have a luxury to use
XmlTextWriter.
Yes, I get your point :-)

But I have 2 reasons to believe in my very simplistic solution:
- The example Scott provides is a serie of commands. They don't seem to have
any special chars. Special chars like "&", ">" and "<". In his particular
case, he may have no escapes to deal with.
- The resulting code is very "readable".

To deal with escape chars, you can use the following function:

StringBuilder xml=new StringBuilder();
xml.Append("<CommandXML>\n");
xml.Append(" <cmd name=\"1\" action=\"2\">\n");
xml.Append(" <arg name=\"3\"
value=\""+ParseForXml("&<>&&&")+"\"/>\n");
xml.Append(" <arg name=\"5\" value=\"6\"/>\n");
xml.Append(" </cmd>\n");
xml.Append(" <cmd name=\"7\" action=\"9\">\n");
xml.Append(" <arg name=\"9\" value=\"0\"/>\n");
xml.Append(" </cmd>\n");
xml.Append("</CommandXML>");

Then you have to define the ParseForXml method somewhere:

public static string ParseForXML(string str) {
string s;
int n1,n2,n3;
StringBuilder xml;
if (str==null) return "";
if (str.Length==0) return "";
xml=new StringBuilder("");

//.......................... Remplace les "&"
.............................................
// Les "&" sont légaux sous la forme "&amp;", "&lt;" et "&gt;"
// Les "&" sont aussi légaux sous la forme "&#--" et "&#x----"
n3=0;
n1=str.IndexOf("&");
while (n1>=0) {
xml.Append(str.Substring(n3,n1-n3));
n3=n1+1;
n2=str.IndexOf(";",n1);
if (n2>n1) {
s=str.Substring(n1,n2-n1+1);
switch (s) {
case "&amp;":
case "&gt;":
case "&lt;":
xml.Append("&");
break;
default:
if (s[1]=='#')
xml.Append("&");
else
xml.Append("&amp;");
break;
}
} else
xml.Append("&amp;");
n1=str.IndexOf("&",n3);
}
xml.Append(str.Substring(n3));

//................. Remplace les ">" et les "<"
..................................
xml.Replace("<","&lt;");
xml.Replace(">","&gt;");

//................................ Et voilà
......................................
return xml.ToString();
}

Of course, if the Xml data you have to write has external namespaces, really
complex Unicode chars, etc, it may get tricky. And, truely, the
XmlTextWriter may be a nice solution:

xml=new StringBuilder();
sw=new StringWriter(xml);
xtw=new XmlTextWriter(sw);
xtw.WriteStartDocument(true);
xtw.WriteStartElement("CommandXML");
xtw.WriteStartElement("cmd");
xtw.WriteAttributeString("name","1");
xtw.WriteAttributeString("action","2");
xtw.WriteStartElement("arg");
xtw.WriteAttributeString("name","3");
xtw.WriteAttributeString("value","4");
xtw.WriteEndElement();
xtw.WriteStartElement("arg");
xtw.WriteAttributeString("name","5");
xtw.WriteAttributeString("value","6");
xtw.WriteEndElement();
xtw.WriteEndElement();
xtw.WriteStartElement("cmd");
xtw.WriteAttributeString("name","7");
xtw.WriteAttributeString("action","9");
xtw.WriteStartElement("arg");
xtw.WriteAttributeString("name","9");
xtw.WriteAttributeString("value","0");
xtw.WriteEndElement();
xtw.WriteEndElement();
xtw.WriteEndDocument();

XmlDocument doc=new XmlDocument();
doc.LoadXml(xml.ToString());

But I think is poorly readable. And I still prefere the simple way. After
all Scott was asking for the "simplest".

"Oleg Tkachenko [MVP]" <oleg@NO!SPAM!PLEASEtkachenko.com> wrote in message
news:O%******************@TK2MSFTNGP09.phx.gbl...
jmgonet wrote:
Well, may be I'm simplistic, but if you just want to send a string to a
server, then build the string:
Bad idea. Then you must take care of XML syntax issues - well-formdness,
escaping special characters, encoding issues etc etc etc. It's always
much better to let XML API to deal with XML.
StringBuilder xml=new StringBuilder();
xml.Append("<CommandXML>\n");


That's a code from 1998. In 2005 you can have a luxury to use

XmlTextWriter.
--
Oleg Tkachenko [XML MVP, MCP]
http://blog.tkachenko.com

Nov 12 '05 #6
jmgonet,
As Oleg suggests using a StringBuilder is a "bad" idea. In addition to the
reasons Oleg states. Item #29 "Always Use a Parser" from Elliotte Rusty
Harold's book "Effective XML - 50 Specific Ways to Improve Your XML" from
Addison Wesley lists a number of other reasons to use a parser. Although
Item #29 is largely reading, I find the topic apropos to writing also.

Hope this helps
Jay
"jmgonet" <jm*****@yahoo.com> wrote in message
news:42**********************@news.sunrise.ch...
| Hello Scott,
|
| Well, may be I'm simplistic, but if you just want to send a string to a
| server, then build the string:
|
| StringBuilder xml=new StringBuilder();
| xml.Append("<CommandXML>\n");
| xml.Append(" <cmd name=\"1\" action=\"2\">\n");
| xml.Append(" <arg name=\"3\" value=\"4\"/>\n");
| xml.Append(" <arg name=\"5\" value=\"6\"/>\n");
| xml.Append(" </cmd>\n");
| xml.Append(" <cmd name=\"7\" action=\"9\">\n");
| xml.Append(" <arg name=\"9\" value=\"0\"/>\n");
| xml.Append(" </cmd>\n");
| xml.Append("</CommandXML>");
|
| Then, when you want to access the string you do a
| xml.ToString();
|
| And, if you want to check the Xml you do a:
| try {
| XmlDocument doc=new XmlDocument();
| doc.LoadXml(xml.ToString());
| } catch (XmlException e) {
| throw new Exception("Error "+e.Message+" in line "+e.LineNumber+"
| at\n"+xml.ToString());
| }
|
| Hope this helps,
| jmgonet
|
|
Nov 12 '05 #7
jmgonet wrote:
But I have 2 reasons to believe in my very simplistic solution:
- The example Scott provides is a serie of commands. They don't seem to have
any special chars. Special chars like "&", ">" and "<".


Not only these. What about " within an attribute value, delimited by ""?
Or ' within an attribute value delimited by ''? What about -- within a
comment? There are lots of tricky cases you better never touch, because
that's XML API responsibility to hide them from you.

Sure you can build XML with no XML API, but then don't be surprised if
your application fails in production when user enters ♫ character in a
form.

So despite your approach looks simpler, it's more complex, becuase it's
too fragile you'd need to fix it all the time.
--
Oleg Tkachenko [XML MVP, MCP]
http://blog.tkachenko.com
Nov 12 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
16603
by: shank | last post by:
What's the easiest way to generate CSV or a comma delimited file from an ASP recordset? I've seen a few searching the internet and they appear to be overkill or out of date. thanks
7
11453
by: Rolf Hemmerling | last post by:
Hello ! Beginner's question: What ist the easiest way to store and save objects in a file generated by a C++ program, by using the "standard C++ library" and/or "Standard Template Library (...
29
3706
by: Lauren Wilson | last post by:
Does anyone know how the following info is extracted from the user's computer by a Front Page form? HTTP User Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107...
2
3982
by: Breda Photo Fair | last post by:
I am looking voor a database software tool which automatically generates unique barcodes to each contact. I should be able to manage the contacts by reading the barcode. The tools will be used to...
4
2279
by: Zoltan Hernyak | last post by:
Hi, Can I generate a new type (a class with fields only) on-the-fly, from a running app, and use it right then? For example if I want to build a class which consists of fields which are...
5
1309
by: Scott M. Lyon | last post by:
Quick (hopefully easy) question for you guys. What is going to be the quickest/easiest way to generate XML from VB.NET? Note: I don't mean an XML file, but XML in memory somehow (an...
3
1162
by: Rajiv Das | last post by:
C# 2.0 XP SP2 In My Code, I am using HttpWebRequest to visit a particular URL. I am required to generate a snapshot image (if this request were made through say IE) and save as jpeg. About .1...
5
1834
by: ken | last post by:
how ASP.NET to generate excel report(office 2003) to client what component i need to reference into the asp.net application and what component i need to install to the server? Moreover, does it...
17
5227
by: Petyr David | last post by:
Just looking for the simplest. right now my perl script returns an error messge to the user if the date string is invalid. would like to do this before accessing the server. TX
0
7090
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7116
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7161
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6825
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7275
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
4857
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3058
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3063
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
595
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.