我需要在现有的XML架构中添加一些标签并将其写入文件。 但是,我需要为每个现有架构添加标签。在C#中实现它的最佳方法是什么?
谢谢!
我有以下代码来解析架构:
/// <summary>
/// Iterates over all elements in a XmlSchema and prints them out
/// </summary>
/// <param name="schema"></param>
private void IterateOverSchemaElements(XmlSchema schema)
{
XmlSchemaComplexType complex;
foreach (XmlSchemaObject schemaObj in schema.Items)
{
complex = schemaObj as XmlSchemaComplexType;
if (complex != null)
{
if (OutputTextDelegate != null)
{
OutputTextDelegate(string.Format("ComplexType: {0}", complex.Name));
}
complex.Annotation = new XmlSchemaAnnotation();
//Get sequence of the complextype:
XmlSchemaSequence sequence = complex.ContentTypeParticle as XmlSchemaSequence;
if (sequence != null)
{
// Iterate over each XmlSchemaElement in the Items collection.
foreach (XmlSchemaElement childElement in sequence.Items)
{
if (OutputTextDelegate != null)
{
OutputTextDelegate(string.Format("--Element: {0}", childElement.Name));
}
}
}
}
}
}
答案 0 :(得分:1)
最好将模式操作为XML文档,而不是模式。例如,此代码在每个元素定义下创建一个注释,该元素定义是复杂类型中序列的一部分:
const string uri = "http://www.w3.org/2001/XMLSchema";
XmlDocument d = new XmlDocument();
d.Load(path);
XmlNamespaceManager ns = new XmlNamespaceManager(d.NameTable);
ns.AddNamespace("xs", uri);
foreach (XmlElement ct in d.SelectNodes("//xs:complexType", ns))
{
foreach (XmlElement e in ct.SelectNodes("xs:sequence/xs:element", ns))
{
XmlElement a = d.CreateElement("xs", "annotation", uri);
a.InnerText = String.Format(
"Complex type: {0}; Element name: {1}",
ct.GetAttribute("name"),
e.GetAttribute("name"));
e.AppendChild(a);
}
}