将XML数据从API解析/反序列化为对象 - XML文档中存在错误(1871,60)

时间:2016-03-23 15:51:06

标签: c# xml serialization

我正在使用XML api,它返回以下内容:

<inventory>
    <product inventoryId="1722474"  externalReference="SM" site="global" total="0" allocated="0" available="0" frozen="0" onOrder="0" lastStockChangeId="505401" lastLineRequirementChangeId="0"/>
    <product inventoryId="1722476"  externalReference="PM" site="global" total="0" allocated="0" available="0" frozen="0" onOrder="0" lastStockChangeId="243256" lastLineRequirementChangeId="0"/>
    .... 1000s of nodes ....
</inventory>

因此,从这个返回的xml节点,我只对以下字段/属性externalReferenceavailable感兴趣。

因此;我创建了以下类来描述我要反序列化/解析的xml内容:

[XmlRoot(ElementName = "product")]
public class StockLevelProduct
{
    [XmlAttribute(AttributeName = "externalReference")]
    public string ExternalReference { get; set; }

    [XmlAttribute(AttributeName = "available")]
    public string Available { get; set; }
}

[XmlRoot(ElementName = "inventory")]
public class StockLevelResult
{
    [XmlElement(ElementName = "product")]
    public List<StockLevelProduct> Product { get; set; }
}

然后我把它们全部放在一起:

// Init
StockLevelResult stockLevelResult;

// Anticipate errors
try
{
    // Generate request url
    string requestUrl = string.Format("{0}/remotewarehouse/inventory.xml?channel={1}",
        apiUrl,
        apiChannel);

    // Call api
    string apiResultXmlString = ApiGet(requestUrl);

    // Fix api result xml string
    if (!apiResultXmlString.Contains("<?xml"))
        apiResultXmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + apiResultXmlString;

    // Deserialize xml string to object
    stockLevelResult = XmlParser.Parse<StockLevelResult>(apiResultXmlString);
}
catch (Exception ex)
{
    Console.WriteLine("Failed to download stock levels - " + ex.Message);
}

注意* API服务器返回的xml字符串不包含<?xml version="1.0" encoding="UTF-8"?>,因此我手动添加它。请注意XmlParser.Parse是否需要它。

执行此代码时;我抛出以下异常:

  

XML文档(1871,60)中存在错误

为什么这不起作用的任何想法?这是返回的XML字符串的问题吗?或者我试图解析/反序列化的方式?

2 个答案:

答案 0 :(得分:0)

试试这个

XmlSerializer xs = new XmlSerializer(typeof(StockLevelResult));
StringReader sReader = new StringReader(apiResultXmlString);
XmlTextReader reader = new XmlTextReader(sReader);
stockLevelResult = (StockLevelResult)xs.Deserialize(reader);

答案 1 :(得分:0)

异常是由api XML响应中的错误数据引起的:

  

<product inventoryId="1726460" externalReference="V02002B&R" site="global" total="0" allocated="0" available="0" frozen="0" onOrder="0" lastStockChangeId="76231" lastLineRequirementChangeId="0"/>

即。此属性&

中的externalReference="V02002B&R"

我修复了它,感谢this answer这样:

// Call api
string apiResultXmlString = ApiGet(requestUrl);

// Fix api result xml string
if (!apiResultXmlString.Contains("<?xml"))
    apiResultXmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + apiResultXmlString;

// Fix bad response data
string pattern = "(?<start>>)(?<content>.+?(?<!>))(?<end><)|(?<start>\")(?<content>.+?)(?<end>\")";
apiResultXmlString = System.Text.RegularExpressions.Regex.Replace(apiResultXmlString, pattern, m =>
            m.Groups["start"].Value +
            System.Web.HttpUtility.HtmlEncode(System.Web.HttpUtility.HtmlDecode(m.Groups["content"].Value)) +
            m.Groups["end"].Value);