我正在尝试使用 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();
}
最佳答案
您想控制输出的 XML 前缀。 For reference an MSDN site
基本上,您只需将 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# 中进行了测试,如果有语法错误,我们深表歉意)
关于c# - XAttribute 生成虚假前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15559320/