如何使用linq xml向XML添加名称空间 [英] How to add namespace to xml using linq xml
本文介绍了如何使用linq xml向XML添加名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题更新:非常抱歉,如果我的问题不清楚
Question update: im very sorry if my question is not clear
这是我现在正在使用的代码
here is the code im using right now
XDocument doc = XDocument.Parse(framedoc.ToString());
foreach (var node in doc.Descendants("document").ToList())
{
XNamespace ns = "xsi";
node.SetAttributeValue(ns + "schema", "");
node.Name = "alto";
}
这是输出
<alto p1:schema="" xmlns:p1="xsi">
我的目标是这样
xsi:schemaLocation=""
p1
和xmlns:p1="xsi"
来自何处?
推荐答案
撰写时
XNamespace ns = "xsi";
这将创建一个XNamespace
,其URI仅为"xsi".那不是你想要的.您希望通过xmlns
属性使用xsi
...的名称空间别名为xsi
...,并带有适当的URI.所以你想要:
That's creating an XNamespace
with a URI of just "xsi". That's not what you want. You want a namespace alias of xsi
... with the appropriate URI via an xmlns
attribute. So you want:
XDocument doc = XDocument.Parse(framedoc.ToString());
foreach (var node in doc.Descendants("document").ToList())
{
XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
node.SetAttributeValue(XNamespace.Xmnls + "xsi", ns.NamespaceName);
node.SetAttributeValue(ns + "schema", "");
node.Name = "alto";
}
或者更好,只需在根元素上设置别名:
Or better, just set the alias at the root element:
XDocument doc = XDocument.Parse(framedoc.ToString());
XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
doc.Root.SetAttributeValue(XNamespace.Xmlns + "xsi", ns.NamespaceName);
foreach (var node in doc.Descendants("document").ToList())
{
node.SetAttributeValue(ns + "schema", "");
node.Name = "alto";
}
创建文档的示例:
using System;
using System.Xml.Linq;
public class Test
{
static void Main()
{
XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
XDocument doc = new XDocument(
new XElement("root",
new XAttribute(XNamespace.Xmlns + "xsi", ns.NamespaceName),
new XElement("element1", new XAttribute(ns + "schema", "s1")),
new XElement("element2", new XAttribute(ns + "schema", "s2"))
)
);
Console.WriteLine(doc);
}
}
输出:
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<element1 xsi:schema="s1" />
<element2 xsi:schema="s2" />
</root>
这篇关于如何使用linq xml向XML添加名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文