简体   繁体   English

如何使用linq xml向XML添加名称空间

[英]How to add namespace to xml using linq 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";
}

and here is the output 这是输出

<alto p1:schema="" xmlns:p1="xsi">

my goal is like this 我的目标是这样的

xsi:schemaLocation=""

where does the p1 and xmlns:p1="xsi" came from? p1xmlns:p1="xsi"来自何处?

When you write 当你写

XNamespace ns = "xsi";

That's creating an XNamespace with a URI of just "xsi". 这将创建一个URI为“ xsi”的XNamespace That's not what you want. 那不是你想要的。 You want a namespace alias of xsi ... with the appropriate URI via an xmlns attribute. 您希望通过xmlns属性使用适当的URI来命名xsi ...的名称空间别名 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";
}

Sample creating a document: 创建文档的示例:

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);
    }
}

Output: 输出:

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <element1 xsi:schema="s1" />
  <element2 xsi:schema="s2" />
</root>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM