我是一个尝试从xml文件创建XDocument类型的xml新手。
我可以针对架构验证xml。
public class XmlHandler
{
public XDocument Read(string filename, string schemaname)
{
var schemas = this.GetSchemas(schemaname);
var doc = XDocument.Load(filename);
var invalid = false;
doc.Validate(schemas,
(o, args) =>
{
this.OnValidationErrors(o, args);
invalid = true;
});
return invalid ? new XDocument() : doc;
}
public XmlSchemaSet GetSchemas(string schemaname)
{
var schemas = new XmlSchemaSet();
schemas.Add(null, schemaname);
return schemas;
}
private void OnValidationErrors(object sender, ValidationEventArgs e)
{
Debug.Print("Errors: ", e);
}
}
但是XDocument的结构似乎是错误的。
运行此代码时
[Fact]
public void Read_get_elements()
{
var sut = new XmlHandler();
var result = sut.Read(this.TestFile, this.TestFileSchema);
var root = result.Root;
var elements = result.Elements();
var nodes = result.Nodes();
var descendants = result.Descendants();
Assert.NotEmpty(elements);
}
根变量包含完整的xml字符串,其他IEnumerable变量保持为空。我错过了什么?
编辑: 这是xml和xsd
的一部分<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="https://www.eurexchange.com/members/releases/eurex14/manuals_technical_en.html"
xmlns="https://www.eurexchange.com/members/releases/eurex14/manuals_technical_en.html"
elementFormDefault="qualified">
<xs:include schemaLocation="eurex_reports_common_structs.xsd"/>
<xs:complexType name="cb020Type">
<xs:annotation>
<xs:documentation>CB020 Position Summary</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element name="rptHdr" type="rptHdrType" />
<xs:element name="cb020Grp" type="cb020GrpType" minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
<xs:element name="cb020" type="cb020Type"/>
<xs:complexType name="cb020GrpType">
<xs:sequence>
<xs:element name="cb020KeyGrp" type="cb020KeyGrpType" />
<xs:element name="cb020Grp1" type="cb020Grp1Type" minOccurs="1" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
</xs:schema>
这是xml的一部分
<?xml version="1.0" encoding="UTF-8"?>
<cb020 xmlns="https://www.eurexchange.com/members/releases/eurex14/manuals_technical_en.html">
<rptHdr>
<exchNam>EUREX</exchNam>
<envText>P</envText>
<rptCod>CB020</rptCod>
<rptNam>Position Summary</rptNam>
<membLglNam>Cyberdyne Systems</membLglNam>
<rptPrntEffDat>2011-12-05</rptPrntEffDat>
<rptPrntRunDat>2011-12-05</rptPrntRunDat>
</rptHdr>
<cb020Grp>
<cb020KeyGrp>
...
</cb020KeyGrp>
<cb020Grp1>
...
</cb020Grp1>
</cb020Grp>
</cb020>