为字符串创建XMLSchema
本文关键字:XMLSchema 创建 字符串 | 更新日期: 2023-09-27 18:26:20
我想为字符串创建XMLSchema,
String parameter="<root><HostName>Arasanalu</HostName><AdminUserName>Administrator</AdminUserName>
<AdminPassword>A1234</AdminPassword><PlaceNumber>38</PlaceNumber></root>"
我们可以自动添加更多的元素
因为我们有上面字符串的静态模式将是
@"<xs:schema xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<xs:element name=""root"">
<xs:complexType>
<xs:sequence>
<xs:element name=""HostName"" type=""xs:string"" />
<xs:element name=""AdminUserName"" type=""xs:string"" />
<xs:element name=""AdminPassword"" type=""xs:string"" />
<xs:element name=""PlaceNumber"" type=""xs:positiveInteger"" />
</xs:sequence>
</xs:complexType>
</xs:element></xs:schema>"
如果我向字符串Parameter添加更多元素。如何在运行时生成架构?。
您可以尝试用DataSet
读取它,编写模式,最后稍微调整一下XML结构。
class Program
{
const string
MinOccurs = "minOccurs",
Element = "element",
LocalName = "xs";
static void Main(string[] args)
{
String parameter =
@"<HostName>Arasanalu</HostName>
<AdminUserName>Administrator</AdminUserName>
<AdminPassword>A1234</AdminPassword>
<PlaceNumber>38</PlaceNumber>";
var ds = new DataSet();
ds.ReadXml(new StringReader("<root>" + parameter + "</root>"));
var sb = new StringBuilder();
using (var w = new StringWriter(sb))
{
ds.WriteXmlSchema(w);
var doc = XDocument.Parse(sb.ToString());
doc.Root.LastNode.Remove();
doc.Root.Attributes()
.Where(a => a.Name.LocalName != LocalName).Remove();
doc.Descendants(XName.Get(Element,
doc.Root.GetNamespaceOfPrefix(LocalName).NamespaceName))
.ToList()
.ForEach(e =>
{
var minOccurs = e.Attribute(XName.Get(MinOccurs));
if (minOccurs != null)
minOccurs.Remove();
});
sb.Clear();
doc.Save(w);
Console.WriteLine(sb.ToString());
}
}
}