我正在加载xml文件,例如
<?xml version="1.0" encoding="UTF-8"?>
<OrderHeadUpload xmlns="http://www.sample-package.org" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Number>Z-00006453580748</Number>
<Number_confirm>000033477</Number_confirm>
<Positions>
<id>168816</Product_id>
<Tare_id>2442</Tare_id>
</Positions>
</OrderHeadUpload>
进行2个班级
[XmlRoot(ElementName = "Head", Namespace = "http://www.sample-package.org")]
public class OrderHeadUpload
{
[XmlElement(ElementName = "Number_confirm", Namespace = "http://www.sample-package.org")]
public string Client_id { get; set; }
[XmlElement(ElementName = "Number", Namespace = "http://www.sample-package.org")]
public string Barcode_id { get; set; }
}
[XmlRoot(ElementName = "Positions", Namespace = "http://www.sample-package.org")]
public class Positions
{
[XmlElement(ElementName = "id", Namespace = "http://www.sample-package.org")]
public string id { get; set; }
[XmlElement(ElementName = "Tare_id", Namespace = "http://www.sample-package.org")]
public string Tare_id {get; set;}
}
我正在加载xml文件(temp.xml),然后在类2 Position和Head上进行序列化
然后是StringReader,它从文件中读取字符串
然后将var position = (Positions) serializer.Deserialize (reader);
类序列化为反序列化
doc.Load(temp);
XmlSerializer serializer = new XmlSerializer(typeof(Positions));
XmlSerializer serializer2 = new XmlSerializer(typeof(Head));
StringReader reader = new StringReader(temp);
var position = (Positions)serializer.Deserialize(reader);
var Head = (OrderHeadUpload)serializer2.Deserialize(reader);
但是我看到错误 错误消息错误XML文档(1,1)中存在错误。 哪里?:在System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader,字符串encodingStyle,XmlDeserializationEvents事件) 在System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader) 在.cs:第64行(var position =(Positions)serializer.Deserialize(reader);)
如何正确反序列化此xml?
答案 0 :(得分:0)
尝试:
[XmlRoot(ElementName = "Positions", Namespace = "http://www.sample-package.org")]
public class Positions
{
[XmlElement(ElementName = "id", Namespace = "http://www.sample-package.org")]
public string id { get; set; }
[XmlElement(ElementName = "Tare_id", Namespace = "http://www.sample-package.org")]
public string Tare_id { get; set; }
}
[XmlRoot(ElementName = "Head", Namespace = "http://www.sample-package.org")]
public class OrderHeadUpload
{
[XmlElement(ElementName = "Number_confirm", Namespace = "http://www.sample-package.org")]
public string Client_id { get; set; }
[XmlElement(ElementName = "Number", Namespace = "http://www.sample-package.org")]
public string Barcode_id { get; set; }
[XmlElement(ElementName = "Positions")]
public Positions positions;
}
使用:
var order = (OrderHeadUpload)serializer.Deserialize(reader);
您只需使用OrderHeadUpload
反序列化一次。如果您有多个职位,则可以像List<T>