2

我正在尝试使用 linq to xml 生成一段 xml 数据。

XNamespace xsins = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
XAttribute xsiniltrue = new XAttribute(xsins+"Exists", "true");
XElement elem = new XElement("CustomerRecord", xsiniltrue);

这会在运行时为 xsins 生成前缀,它们看起来很假。

<Fragment>
    <CustomerRecord p5:Exists="true" xmlns:p5="w3.org/2001/XMLSchema-instance"; /> 
</Fragment> 
<Fragment> 
    <CustomerRecord p3:Exists="false" xmlns:p3="w3.org/2001/XMLSchema-instance"; /> 
</Fragment>

合并为

<Fragment xmlns:p5="w3.org/2001/XMLSchema-instance";  >
    <CustomerRecord p5:Exists="true" /> 
    <CustomerRecord p5:Exists="false" /> 
</Fragment>

还尝试使用 XMLWriter,

XNamespace xsins = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");

using (var writer = XmlWriter.Create(fullPath, settings))
{
    writer.WriteStartDocument(true);
    writer.WriteStartElement(string.Empty, "Company", "urn:schemas-company");
    //writer.WriteAttributeString(xsins.GetName("xsi"), "http://www.w3.org/2001/XMLSchema-instance");

    writer.WriteStartElement(string.Empty, "Add", "urn:schemas-company");
    foreach (var qx in resultXMLs)
    {
        qx.WriteTo(writer);
    }

    writer.WriteEndElement();
    writer.WriteEndElement();
    writer.WriteEndDocument();
}

我终于破解了它(至少我希望),下面的部分解决了我的问题

using (var writer = XmlWriter.Create(fullPath, settings))
{
    writer.WriteStartDocument(true);
    writer.WriteStartElement(string.Empty, "Company", "urn:schemas-company");
    writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
    writer.WriteStartElement(string.Empty, "Add", "urn:schemas-company");
    foreach (var qx in fragments)
    {
        qx.SetAttributeValue(XNamespace.Xmlns + "xsi", xsins.ToString());
        qx.WriteTo(writer);
    }
    writer.WriteEndElement();
    writer.WriteEndElement();
    writer.WriteEndDocument();
}
4

1 回答 1

1

您想要控制输出的 XML 前缀。供参考 MSDN 站点

基本上你只需要添加xml:xsi到你的根节点,然后 Linq to XML 就可以完成剩下的工作。

请注意,当您遇到非常复杂的示例时,它往往会崩溃,但它应该在这种情况下工作。

编辑:

要删除无关的属性,您可以简单地手动完成:

foreach(var element in root.Descendents())
{
    foreach (var attribute in element.Attributes())
    {
        if (attribute.Name.Namespace == XNamespace.Xmlns)
           attribute.Remove();
    }
}

注意上面是粗略的,我手边没有 XML 项目。

编辑:

我不确定您的输入是什么,但这里有一个硬编码您的预期输出的示例:

var xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
var fragment =
      new XElement("Fragment",
                   new XAttribute(XNamespace.Xmlns + "p5", xsi.ToString()),
                   new XElement("CustomerRecord",
                                new XAttribute(xsi + "Exists", "true")),
                   new XElement("CustomerRecord",
                                new XAttribute(xsi + "Exists", "false")));

我对此进行了测试,它的输出与您要求的相同(我在 F# 中进行了测试,如果有语法错误,请见谅)

于 2013-03-21T22:30:57.987 回答