我正在尝试使用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();
}
答案 0 :(得分:1)
您想要控制输出的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#中进行了测试,很抱歉,如果存在语法错误)