問題描述
我現在已經搜索了一些,但我無法找到以編程方式從 XML 模式自動生成數據的方法.假設我有這個 XML 模式:
I have searched for a bit now, but i'm not able to find a way to autogenerate data from a XML Schema programmatically. Lets say I have this XML schema:
<xs:element xmlns:xs="http://www.w3.org/2001/XMLSchema" name ="Persons">
<xs:complexType>
<xs:sequence>
<xs:element name="Person">
<xs:complexType>
<xs:sequence>
<xs:element name="FirstName" type="xs:string" />
<xs:element name="LastName" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
我可以使用 VS 函數生成示例 XML"由此創建一個 XML
有沒有辦法以編程方式做到這一點?
I am able to create a XML from this using the VS function "Generate Sample XML"
Is there a way to do this programmatically?
指定.我不想自己創建所有對象并以編程方式插入數據.我希望它能夠像 VS 中的生成示例 XML"一樣自動創建對象和屬性.這樣做的原因是我想更改 XSD 而不必對 xml 樣本生成做任何事情.
To specify. I do not want to create all the objects and insert data programmatically myself. I would like for it to create the objects and attributes automatically just like the "Generate Sample XML" in VS. The reason for this is that i would like to change the XSD without having to do anything about xml sample generation.
推薦答案
經過一番搜索.我找到了一個實現 xml 示例生成器的 項目.我創建了一個測試解決方案并導入了這些類.然后我刪除了 XmlGen.cs 文件并創建了我自己的 main 方法.輸出將基于根元素.
after doing some searching. I have found a project that have implemented a xml sample generator. I created a test solution and imported the classes. Then i deleted the XmlGen.cs file and created my own main method. The output will be based on the root element.
public static void Main(string[] args)
{
using (var stream = new MemoryStream(File.ReadAllBytes("schema.xsd")))
{
var schema = XmlSchema.Read(XmlReader.Create(stream ), null);
var gen = new XmlSampleGenerator(schema, new XmlQualifiedName("rootElement"));
gen.WriteXml(XmlWriter.Create(@"c: empautogen.xml"));
Console.WriteLine("Autogenerated file is here : c: empautogen.xml");
}
}
這篇關于以編程方式從 XML Schema 生成測試 XML的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!