开发者

escaping an apostrophe in XML attributes

Trying to load some XML into a document:

<Custom AttributeA='' AttributeB='Bob' AttributeC='HUNTER开发者_如何转开发S' COMPANY EMPLOYEES' 403B PLAN' />

Then when I try to add it to a document:

XmlDocument xmlCustom = new XmlDocument();
xmlCustom.LoadXml(customNode);

I end up getting an error message System.Xml.XmlException: 'COMPANY' is an unexpected token. The expected token is '='. The value of AttributeC is supposed to be: HUNTERS' COMPANY EMPLOYEES' 403B PLAN

I tried replacing the ' previously before loading the XML but it replaces ALL of the apostrophe's and AttributeA='' is equally invalid.

EDIT: Yes, I would agree on poorly formed but it is what I have to work with.


You can use

<Custom AttributeC="HUNTERS&apos; COMPANY EMPLOYEES'&apos; 403B PLAN"/>

or

<Custom AttributeC="HUNTERS' COMPANY EMPLOYEES' 403B PLAN"/>

or even

<Custom AttributeC='HUNTERS&apos; COMPANY EMPLOYEES&apos; 403B PLAN'/>


There are many many problems with this piece of markup.

This is no XML. XML uses double quotes for attributes (okay, I just learned single quotes are okay, too). But it requires equals-Signs between attribute name and value (see your last attribute). In addition, attribute names cannot contain whitespace, and MUST have a value assigned, unlike in HTML.

Oh, and if there is no closing tag, you have to end the line with />, not just >.

If you want to have an apostrophe in your attributes, you can use escaping, like here:

<gangster name="George &quot;Shotgun&quot; Ziegler">

Or with single quotes (and an escaped single quote):

<ad text='I love McDonald&apos;s'>

Or by using double quotes when you want single quotes in the attributes:

<ad text="I love McDonald's">


Encode the apostrophe as &apos;

<Custom AttributeA='' AttributeB='Bob' AttributeC='HUNTERS&apos; COMPANY EMPLOYEES&apos; 403B PLAN' />


Spaces are not allowed for attribute names. You must type something like this:

<Custom AttributeA='' AttributeB='Bob' AttributeC='HUNTERS&apos; COMPANY EMPLOYEES&apos; 403B PLAN'/>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜