[英]Deserialize a XML fragment to class that has been generated by xsd.exe
I have a xml file that I want to read it and then interpret and convert to respective classes that were generated from xsd tool. 我有一个要读取的xml文件,然后解释并转换为从xsd工具生成的各个类。 Here are the steps which I am trying:
这是我正在尝试的步骤:
I am pasting the code I have worked till now, I seem to get an exception when I am deserializing, {"There is an error in XML document (0, 0)."} 我正在粘贴迄今为止一直使用的代码,在反序列化时似乎出现了一个异常, {“ XML文档(0,0)中存在错误。”}
var doc = XDocument.Load(filePath);
var query2 = from b in doc.Root.Descendants()
select b;
foreach (var item in query2)
{
switch (item.Name.LocalName)
{
case "SomeStringValue":
XmlSerializer srz = new XmlSerializer(typeof(SomeClassGeneratedfromXSD));
var writer=item.CreateReader();
parameterFromFile.SomeProperty = (SomeClassGeneratedfromXSD)srz.Deserialize(writer);
//srz.Deserialize(item);
break;
I am pasting a snippet of what my xsd looked like: 我正在粘贴xsd的摘要:
<xs:complexType name="Parameters">
<xs:all>
<xs:element name="A">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="mstns:Restricted8CharString">
<xs:attribute name="Caption" use="required" fixed="Caption for A">
<xs:simpleType>
<xs:restriction base="xs:string"></xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="ActionWhenMaxReached" use="required">
<xs:simpleType>
<xs:restriction base="xs:short">
<xs:pattern value="[1-3]"></xs:pattern>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="Expression" type="xs:string" default="0" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element name="B">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:short">
<xs:attribute name="Caption" use="prohibited">
<xs:simpleType>
<xs:restriction base="xs:string"></xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="ActionWhenMaxReached" use="required">
<xs:simpleType>
<xs:restriction base="xs:short">
<xs:pattern value="[1-3]"></xs:pattern>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="Expression" type="xs:string" default="0" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:all>
</xs:complexType>
Your closing tag is incorrect. 您的结束标签不正确。 It should be:
它应该是:
</xs:complexType>
and not 并不是
</xs:complexType name="Parameters">
After struggling, I have found out the solution: 经过努力,我找到了解决方案:
Actually I was trying to parse an inner element, which was incorrect; 实际上,我试图解析一个内部元素,这是不正确的。 I was already having the classes from the xsd tool, so I can Simply use the code as:
我已经有了xsd工具中的类,因此可以简单地将代码用作:
XmlSerializer serializer = new XmlSerializer(typeof(RootClass));
using (TextReader reader = new StreamReader(filePath))
{
RootClass parameterFromFile = (RootClass)serializer.Deserialize(reader);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.