Constructing simple XML?

  • Thread starter Thread starter Brett Romero
  • Start date Start date
B

Brett Romero

What is the best way to construct this type of XML

<ROOT><Person PersonId=\"1000\" /><Person PersonId=\"1001\" /><Person
PersonId=\"1002\" /></ROOT>

when I'm getting back only the three numerical values? The is occuring
in a loop and I'm getting a variable such as PersonID, which holds the
values. The XML needs to be a string but I'd like to see what a more
complex type would look like (XMLdoc type?).

Thanks,
Brett
 
Brett, you create attribute nodes just like element nodes. Here's the code
from the link you posted, modified to create the XML in your original post:

XmlDocument xmldoc;
XmlAttribute attr;
XmlElement elem;
XmlElement root;

xmldoc=new XmlDocument();

//let's add the XML declaration section
XmlNode xmlnode=xmldoc.CreateNode(XmlNodeType.XmlDeclaration,"","");
xmldoc.AppendChild(xmlnode);

//let's add the root element
elem=xmldoc.CreateElement("ROOT");
xmldoc.AppendChild(elem);
root = elem;

//add person elements. assume you have some data structure called ListOfIds
containing the numbers
foreach (int personId in ListOfIds)
{
elem = xmldoc.CreateElement("Person");
attr = xmldoc.CreateAttribute("PersonId");
attr.InnerText = personId.ToString();
elem.Attributes.Append(attr)
root.AppendChild(elem);
}

--
Kai Brinkmann [MSFT]

Please do not send e-mail directly to this alias. This alias is for
newsgroup purposes only.
This posting is provided "AS IS" with no warranties, and confers no rights.
 
Thanks.

If I try to read my file, which looks like this:
<?xml version="1.0"?>
<ROOT>
<Person PersonID="83615">
</Person>
</ROOT>

I get this error:
"The data at the root level is invalid. Line 1, position 1."

I'm using:
xmlDoc.LoadXml(@"C:\Documents and Settings\BROMERO\My
Documents\testing.spec");

I'm not sure if it is referring to the LoadXML method or the file. Any
ideas?

The <?xml version="1.0"?> part was generated with the XMLDeclaration
enumerator.

Thanks,
Brett
 
Hi Brett,
the LoadXML method assumes the string you are passing as a parameter is
XML, not a file path. If you want to load XML from a file use the
XmlDocument.Load method and pass in the file name.

Hope that helps
Mark Dawson
http://www.markdawson.org
 
For really quick XML construction, I suggest looking at the XmlWriter class
(and its descending implementations).
 

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

Back
Top