Reputation: 20078
I'm having hard-time fixing this little problem of ampersand (&) in the url... I'm serializing XML as shown below...
var ser = new XmlSerializer(typeof(response));
using (var reader = XmlReader.Create(url))
{
response employeeResults = (response)ser.Deserialize(reader); //<<error when i pass with ampersand
}
the above codes works fine if there is no &
in the url otherwise it throws me an error (see below)
i have no problem serializing this url:
http://api.host.com/api/employees.xml/?&search=john
I'm having problem with this url:
http://api.host.com/api/employees.xml/?&max=20&page=10
The error i'm getting is:
`There is an error in XML document (1, 389).`
PS: I did tried passing &
and also tried with &
or #026
or &
- no luck.
Upvotes: 6
Views: 7320
Reputation: 56212
This XML isn't well-formed:
<?xml version="1.0"?>
<response xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Api">
<meta>
<status>200</status>
<message />
<resultSet>
<Checked>true</Checked>
</resultSet>
<pagination>
<count>1</count>
<page>1</page>
<max>1</max>
<curUri>http://api.host.com/employee.xml/?&max=5</curUri>
<prevUri i:nil="true"/>
<nextUri>http://api.host.com/employee.xml/?&max=5&page=2</nextUri>
</pagination>
</meta>
<results i:type="ArrayOfemployeeItem">
<empItem>
<Id>CTR3242</Id>
<name>john</name>
......
</empItem>
</results>
</response>
You must escape &
character or put entire string in CDATA
, e.g.:
<?xml version="1.0"?>
<response xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Api">
<meta>
<status>200</status>
<message />
<resultSet>
<Checked>true</Checked>
</resultSet>
<pagination>
<count>1</count>
<page>1</page>
<max>1</max>
<curUri><![CDATA[http://api.host.com/employee.xml/?&max=5]]></curUri>
<prevUri i:nil="true"/>
<nextUri><![CDATA[http://api.host.com/employee.xml/?&max=5&page=2]]></nextUri>
</pagination>
</meta>
<results i:type="ArrayOfemployeeItem">
<empItem>
<Id>CTR3242</Id>
<name>john</name>
......
</empItem>
</results>
</response>
If you are dealing with some third-party system and not able to get proper XML response, you have to do some pre-processing.
Maybe the simplest way is just replace all &
with &
using string.Replace
method.
Or use this regex &(?!amp;)
to replace all &
excluding correct ones like &
.
Upvotes: 5
Reputation: 391
Have you tried to wrap the Attribute with <![CDATA[yourAttribute]]>
?
& is not allowed in xml
deserialize-xml-with-ampersand-using-xmlserializer
Upvotes: 2