How can I write xml with a namespace and prefix with XElement?

后端 未结 5 1393
北海茫月
北海茫月 2020-12-01 23:31

This may be a beginner xml question, but how can I generate an xml document that looks like the following?



        
相关标签:
5条回答
  • 2020-12-01 23:55

    Try this code:

    string prefix = element.GetPrefixOfNamespace(element.Name.NamespaceName);
    string name = String.Format(prefix == null ? "{1}" : "{0}:{1}", prefix, element.Name.LocalName);`
    
    0 讨论(0)
  • 2020-12-02 00:07

    I hope you will get some useful information from this thread - XElement default namespace on attributes provides unexpected behaviour

    EDIT:

    Another FAQ at - http://social.msdn.microsoft.com/Forums/en-US/xmlandnetfx/thread/c0648840-e389-49be-a3d2-4d5db17b8ffffd

    0 讨论(0)
  • 2020-12-02 00:08

    Here is a small example that creates the output you want:

    using System;
    using System.Xml.Linq;
    
    class Program
    {
        static void Main()
        {
            XNamespace ci = "http://somewhere.com";
            XNamespace ca = "http://somewhereelse.com";
    
            XElement element = new XElement("root",
                new XAttribute(XNamespace.Xmlns + "ci", ci),
                new XAttribute(XNamespace.Xmlns + "ca", ca),
                    new XElement(ci + "field1", "test"),
                    new XElement(ca + "field2", "another test"));
        }
    }
    
    0 讨论(0)
  • 2020-12-02 00:13
    XNamespace ci = "http://somewhere.com";
    XNamespace ca = "http://somewhereelse.com";
    XElement root = new XElement(aw + "root",
        new XAttribute(XNamespace.Xmlns + "ci", "http://somewhere.com"),
        new XAttribute(XNamespace.Xmlns + "ca", "http://somewhereelse.com"),
        new XElement(ci + "field1", "test"),
        new XElement(ca + "field2", "another test")
    );
    Console.WriteLine(root);
    

    This should output

    <root xmlns:ci="http://somewhere.com" xmlns:ca="http://somewhereelse.com">
        <ci:field1>test</ci:field1>
        <ca:field2>another test</ca:field2>
    </root>
    
    0 讨论(0)
  • 2020-12-02 00:15

    For XmlDocument it's similar:

    XmlAttribute attribute1 = sessionXml.CreateAttribute("s", "Attribute1", namespaceURI);
    XmlAttribute attribute2 = sessionXml.CreateAttribute("s", "Attribute2", namespaceURI);
    XmlAttribute attribute3 = sessionXml.CreateAttribute("s", "Attribute3", namespaceURI);
    XmlAttribute attribute4 = sessionXml.CreateAttribute("s", "Attribute4", namespaceURI);
    
    0 讨论(0)
提交回复
热议问题