Problem Xml and &

  • Thread starter Thread starter Christian Havel
  • Start date Start date
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
 
Hi,

I load the Xml from a string, not from a file:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(stringWithXmlContent);
 
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").
 
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)
 
Christian said:
I load the Xml from a string, not from a file:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(stringWithXmlContent);
Makes no difference.
 
Back
Top