How to add namespace to xml using linq xml

前端 未结 1 1278
生来不讨喜
生来不讨喜 2021-01-21 04:37

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());
fore         


        
相关标签:
1条回答
  • 2021-01-21 04:51

    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>
    
    0 讨论(0)
提交回复
热议问题