How to add namespace to xml using linq xml

陌路散爱 提交于 2019-12-20 02:42:42

问题


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?


回答1:


When you write

XNamespace ns = "xsi";

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

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>


来源:https://stackoverflow.com/questions/41136088/how-to-add-namespace-to-xml-using-linq-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!