Creating an XML element with a namespace with XmlDocument.CreateElement()

前端 未结 2 743
孤街浪徒
孤街浪徒 2020-12-04 02:54

I\'m trying to create an XmlDocument using C# and .NET (version 2.0.. yes, version 2.0). I have set the namespace attributes using:

document.Doc         


        
相关标签:
2条回答
  • 2020-12-04 03:02

    You can assign a namespace to your bar element by using XmlDocument.CreateElement Method (String, String, String)

    Example:

    using System;
    using System.Xml;
    
    XmlDocument document = new XmlDocument();
    
    // "foo"                    => namespace prefix
    // "bar"                    => element local name
    // "http://tempuri.org/foo" => namespace URI
    
    XmlElement element = document.CreateElement(
        "foo", "bar", "http://tempuri.org/foo");
    
    document.AppendChild(element);
    Console.WriteLine(document.OuterXml);
    

    Expected Output #1:

    <foo:bar xmlns:foo="http://tempuri.org/foo" />
    

    For a more interesting example, insert these statements before document.AppendChild(element);:

    XmlElement childElement1 = document.CreateElement("foo", "bizz",
        "http://tempuri.org/foo");
    
    element.AppendChild(childElement1);
        
    XmlElement childElement2 = document.CreateElement("foo", "buzz",
        "http://tempuri.org/foo");
    
    element.AppendChild(childElement2);
    

    Expected Output #2:

    <foo:bar xmlns:foo="http://tempuri.org/foo"><foo:bizz /><foo:buzz /></foo:bar>
    

    Note that the child elements bizz and buzz are prefixed with the namespace prefix foo, and that the namespace URI http://tempuri.org/foo isn't repeated on the child elements since it is defined within the parent element bar.

    0 讨论(0)
  • 2020-12-04 03:08

    Maybe you could share what you're expecting as final XML document.

    However from what I understand you want to do that looks like:

        <?xml version="1.0"?>
        <soapMessage xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope">
            <Header xmlns="http://schemas.xmlsoap.org/soap/envelope" />
        </soapMessage>
    

    so the code to do that would be:

        XmlDocument document = new XmlDocument();
        document.LoadXml("<?xml version='1.0' ?><soapMessage></soapMessage>");
        string soapNamespace = "http://schemas.xmlsoap.org/soap/envelope/";
        XmlAttribute nsAttribute = document.CreateAttribute("xmlns","soapenv","http://www.w3.org/2000/xmlns/");
        nsAttribute.Value = soapNamespace;
        document.DocumentElement.Attributes.Append(namespaceAttribute);
        document.DocumentElement.AppendChild(document.CreateElement("Header",soapNamespace));
    
    0 讨论(0)
提交回复
热议问题