DataSet.ReadXml - 错误“输入的字符串格式不正确”

DataSet.ReadXml - Error “input string was not in a correct format”

代码有两个输入

  1. XML 文件
  2. XSD 文件

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>

注意这里AttributeContent不包含值

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

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

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

基本上,XML 文件现在在这种情况下是正确的。

解决方法1.不添加不包含值的属性

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

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

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