数据集.ReadXml -错误"输入字符串格式不正确" &g



代码

有两个输入XML文件
  1. XSD文件
  2. XML内容

<MyFile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<Attribute>
<AttributeName>Text1</AttributeName>
<AttributeContent>1</AttributeContent>
</Attribute>
<Attribute>
<AttributeName>Text1</AttributeName>
<AttributeContent>1</AttributeContent>
</Attribute>
</MyFile> 

与此

对应的XSD内容
<?xml version="1.0"?>
<xs:schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="MyFile">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="unbounded" name="Attribute">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="0" name="AttributeName" type="xs:string" />
<xs:element minOccurs="0" name="AttributeContent" type="xs:decimal" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

在c#中读取XML文件,我使用

DataSet ds = new DataSet();
ds.ReadXmlSchema(new MemoryStream(xmlSourceModel.File2Content));
foreach (DataTable tab in ds.Tables)
{
tab.BeginLoadData();
}
ds.ReadXml(new MemoryStream(xmlSourceModel.File1Content));
foreach (DataTable tab in ds.Tables)
{
tab.EndLoadData(); 
}

在此之后,我期待数据集中的数据。它确实有效。

问题:如果我使用如下的XML内容

<Attribute>
<AttributeName>Text1</AttributeName>
<AttributeContent></AttributeContent>
</Attribute>

请注意,attributeccontent不包含该值。

在这种情况下,ds.ReadXml()方法给出错误"输入字符串格式不正确。">

我们如何解决这个错误,以便我们可以选择空数据?

我们可以设置一些默认数据来避免这个错误吗?

基本上,这个XML文件现在是正确的。

解决方案1。不要添加不包含值

的属性
<Attribute>
<AttributeName>Text1</AttributeName>
</Attribute>

解决方案2,添加xsi: nil ="true"像这样

<Attribute>
<AttributeName>Text1</AttributeName>
<AttributeContent xsi:nil="true"></AttributeContent>
</Attribute>

最新更新