DataSet读入XML的关系(relation):错在哪里?(一晚上都没解决,郁闷中:(
今晚我一直为这样一个问题所困扰:自己编写一个XML文件,其中有两张表,这两张表之间创建有联系(relation)。我想在程序运行期间加载这个xml文件,把它读入到DataSet中,然后通过对控件的数据绑定,把这两张表的关系显示出来。整个过程并不复杂,我的主要代码如下:
private void Form1_Load(object sender, System.EventArgs e)
{
// load the XML file
try
{
ds.ReadXml(@"..\..\PubTitle.xml");
}
catch(Exception ex)
{
MessageBox.Show("Unable to read from PubTitle.xml\n"+ex.Message);
}
// bind the DataSet to Windows controls and display the relationship between two DataTables in DataSet
MessageBox.Show(ds.Relations.Count.ToString());
....
}
问题就出在上面最后的MessageBox.Show()那里(这一行只是为了调试方便而加上的),在这里显示出来的ds.Relations.Count竟然为0!也就是说DataSet无法正确读入XML文件中的关系。可是我在查看MSDN中DataSet.ReadXML()以及DataSet.ReadXMLSchema()的文档时,却说可以加载XML文件的表、关系、约束定义等,请问问题出在哪里?
附:我所用的XML文档结构(内容其实很少,就是一个publishers表,列有pub_id、pub_name、country字段;另有一个titles表,有title_id、title、type、pub_id字段,两表通过pub_id建立关系,其中publishers为主表,我在其它的程序中验证了这个XML文档是有效的):
<?xml version="1.0" standalone="yes" ?>
<xs:schema id="dsPubTitle" targetNamespace="http://www.tempuri.org/dsPubTitle.xsd" xmlns:mstns="http://www.tempuri.org/dsPubTitle.xsd" xmlns="http://www.tempuri.org/dsPubTitle.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" attributeFormDefault="qualified" elementFormDefault="qualified">
<xs:element name="ds" msdata:IsDataSet="true" msdata:Locale="zh-CN">
<xs:complexType>
<xs:choice maxOccurs="unbounded">
<xs:element name="publishers">
<xs:complexType>
<xs:sequence>
<xs:element name="pub_id" type="xs:string" />
<xs:element name="pub_name" type="xs:string" minOccurs="0" />
<xs:element name="country" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="titles">
<xs:complexType>
<xs:sequence>
<xs:element name="title_id" type="xs:string" />
<xs:element name="title" type="xs:string" />
<xs:element name="type" type="xs:string" />
<xs:element name="pub_id" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
<xs:unique name="titles_Constraint1" msdata:ConstraintName="Constraint1" msdata:PrimaryKey="true">
<xs:selector xpath=".//mstns:titles" />
<xs:field xpath="mstns:title_id" />
</xs:unique>
<xs:keyref name="Publisherstitles" refer="mstns:Constraint1">
<xs:selector xpath=".//mstns:titles" />
<xs:field xpath="mstns:pub_id" />
</xs:keyref>
<xs:unique name="Constraint1" msdata:PrimaryKey="true">
<xs:selector xpath=".//mstns:publishers" />
<xs:field xpath="mstns:pub_id" />
</xs:unique>
</xs:element>
</xs:schema>