Problem Xml and &

C

Christian Havel

Hi,

I have a xml file with content like following:

<entities>
<entity created="28.02.2008 14:32:31" crudaction="Create">
<item NAME="field1" VALUE="Huber Gmbh & Co. KG" />
</entity>
</entities>

I try to load the file with XmlDocument.Load(pathToXmlFile) and receive a
Xml Exception because of the &amp.
How the & should look like in the Xml to read it from the file?
Christian
 
C

Christian Havel

Hi,

I load the Xml from a string, not from a file:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(stringWithXmlContent);
 
J

Jeroen Mostert

Christian said:
Hi,

I have a xml file with content like following:

<entities>
<entity created="28.02.2008 14:32:31" crudaction="Create">
<item NAME="field1" VALUE="Huber Gmbh & Co. KG" />
</entity>
</entities>

I try to load the file with XmlDocument.Load(pathToXmlFile) and receive a
Xml Exception because of the &amp.
How the & should look like in the Xml to read it from the file?
Christian

You said it yourself, really.

<entities>
<entity created="28.02.2008 14:32:31" crudaction="Create">
<item NAME="field1" VALUE="Huber Gmbh &amp; Co. KG" />
</entity>
</entities>

The XML standard requires that "&" always be escaped as "&amp;" and that "<"
is always escaped as "&lt;" (numeric references, i.e. "&" are also
allowed). Other quoting is mostly optional and the necessity depends on
context, but these two characters must always be escaped.

The easiest way to achieve this is to *always* use the XML classes for
producing content and *never* string concatenation or other ad-hoc forms of
XML production.

Incidentally, it's a bad idea to pass a time field in local time notation.
Prefer ISO 8601 instead, it's unambiguous:

<entities>
<entity created="2008-02-28T14:32:31" crudaction="Create">
<item NAME="field1" VALUE="Huber Gmbh &amp; Co. KG" />
</entity>
</entities>

Note that this is still missing timezone information. If you don't need
that, it's a good idea to use UTC time as well. So if you're in UTC+1, this
would become

<entities>
<entity created="2008-02-28T13:32:31Z" crudaction="Create">
<item NAME="field1" VALUE="Huber Gmbh &amp; Co. KG" />
</entity>
</entities>

You can easily produce ISO 8601 times with DateTime.ToString("s").
 
M

Martin Honnen

Christian said:
I load the Xml from a string, not from a file:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(stringWithXmlContent);

With XML the ampersand needs to be escaped as &amp; (& a m p; for the
web interface to the newsgroup)
 
J

Jeroen Mostert

Christian said:
I load the Xml from a string, not from a file:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(stringWithXmlContent);
Makes no difference.
 

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

Top