我正在尝试将XML文件(由架构验证)读入数据集的第一个数据表中。执行此操作并在程序中放置断点后,我可以看到数据表有0行。我无法弄清楚为什么会这样......
以下是代码示例:
Public Sub GitRDone(ByVal sqlDT As DataTable)
Dim ds As New DataSet
Dim appPath As String = GetAppPath()
Dim schemaFS As String = appPath & "blah.xsd"
Dim xmlFS As String = appPath & "blah.xml"
Try
ds.Clear()
ds.EnforceConstraints = False
ds.ReadXmlSchema(schemaFS)
ds.ReadXml(xmlFS)
ds.Tables.Add(sqlDT)
Catch e As Exception
MsgBox(e.ToString())
End Try
End Sub
架构示例:
<xsd:schema id="HCR_EmployeesSchema"
elementFormDefault="qualified"
targetNamespace="http://www.tempuri.org/MyDataSet.xsd"
xmlns="http://www.tempuri.org/MyDataSet.xsd"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="Employees" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Employee">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="EmployeeID">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:whiteSpace value="collapse"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
.....and on......
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
XML示例:
<?xml version="1.0" encoding="utf-8"?>
<Employees>
<Employee>
<EmployeeID>blah</EmployeeID>
</Employee>
</Employees>
答案 0 :(得分:1)
你的逻辑中必须有一些微不足道的错误(可能是参数 - 表 - sqlDt - 你添加到数据集,但是为空 - 数据集包含其他表,反序列化并且不为空),序列化按预期工作。示例代码(没有架构,因为您提供了不完整的代码):
using System;
namespace datasetXml
{
static class Program
{
const string xml =
@"<?xml version=""1.0"" encoding=""utf-8""?>
<Employees>
<Employee>
<EmployeeID>blah</EmployeeID>
</Employee>
</Employees>";
static void Main(string[] args)
{
var ds = new System.Data.DataSet();
using (var sr = new System.IO.StringReader(xml))
ds.ReadXml(sr);
Console.WriteLine("rows in table: " + ds.Tables[0].Rows.Count);
}
}
}
以上程序产生输出: 表中的行:1
答案 1 :(得分:0)
好吧,我明白了。我需要更改我的架构属性:
<xsd:schema id="EmployeesSchema"
elementFormDefault="qualified"
targetNamespace="http://www.tempuri.org/MyDataSet.xsd"
xmlns="http://www.tempuri.org/MyDataSet.xsd"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
对此:
<?xml version="1.0" standalone="yes" ?>
<xsd:schema id="Employees" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
这里的根本问题是我的xsd:schema id属性错误。谢谢