問題描述
我正在使用 MSDN
中的這段代碼從 XML 創(chuàng)建 XSD
I am using this piece of code from MSDN
to create an XSD from an XML
XmlReader reader = XmlReader.Create("contosoBooks.xml");
XmlSchemaSet schemaSet = new XmlSchemaSet();
XmlSchemaInference schema = new XmlSchemaInference();
schemaSet = schema.InferSchema(reader);
foreach (XmlSchema s in schemaSet.Schemas())
{
textbox.text = s.ToString();
}
我想根據(jù)我的 xml 文件輸出 .xsd.當我生成 .xsd 文件時,我得到的唯一內(nèi)容是:System.Xml.Schema.XmlSchema
I want to output the .xsd based on my xml file. When I generate the .xsd file, the only content I get inside it is: System.Xml.Schema.XmlSchema
當我使用 Visual Studio 選項生成 XSD 來創(chuàng)建架構(gòu)時,它會正確顯示.但是,我有超過 150 個 xml 文檔需要創(chuàng)建 XSD,因此需要一個編程選項.有人可以幫忙嗎?
When I generate the XSD using Visual Studio option to create Schema, it comes out properly. However, I have over 150 xml docs that I need to create XSD for hence need a programmatic option. Can anyone help?
推薦答案
這就是你缺少的...而不是簡單地執(zhí)行 s.ToString()
,而是這樣做:
This is what you're missing...
instead of simply doing s.ToString()
, do this:
XmlWriter writer;
int count = 0;
foreach (XmlSchema s in schemaSet.Schemas())
{
writer = XmlWriter.Create((count++).ToString() + "_contosobooks.xsd");
s.Write(writer);
writer.Close();
Console.WriteLine("Done " + count);
}
reader.Close();
然后您可以編寫適當?shù)倪壿媮砀鼉?yōu)雅地進行讀/寫,讀取許多 xml 文件并創(chuàng)建相應的 xsd 文件等.
You can then write proper logic to do the read/write more gracefully, read many xml files and create corresponding xsd files, etc.
我從這里獲取了 contosobooks.xml:https://code.google.com/p/code4cs/source/browse/trunk/AppCase/dNet/Xml/data/contosoBooks.xml?spec=svn135&r=135
I took the contosobooks.xml from here: https://code.google.com/p/code4cs/source/browse/trunk/AppCase/dNet/Xml/data/contosoBooks.xml?spec=svn135&r=135
輸出 xsd 為:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://www.contoso.com/books" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="bookstore">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="book">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string" />
<xs:element name="author">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="0" name="name" type="xs:string" />
<xs:element minOccurs="0" name="first-name" type="xs:string" />
<xs:element minOccurs="0" name="last-name" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="price" type="xs:decimal" />
</xs:sequence>
<xs:attribute name="genre" type="xs:string" use="required" />
<xs:attribute name="publicationdate" type="xs:date" use="required" />
<xs:attribute name="ISBN" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
這篇關于在代碼中從 XML 創(chuàng)建 XSD的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!