我正在尝试使用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();
}发布于 2013-03-22 06:30:58
您希望控制输出的XML前缀。For reference an MSDN site
基本上,您只需要将xml:xsi添加到根节点,Linq就可以处理剩下的事情。
请注意,当您进入真正复杂的示例时,它往往会崩溃,但在这种情况下它应该可以工作。
编辑:
要删除无关属性,您可以简单地手动完成:
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#测试的,所以如果有语法错误,很抱歉)
https://stackoverflow.com/questions/15559320
复制相似问题