Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
670 views
in Technique[技术] by (71.8m points)

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

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.DocumentElement.SetAttribute(
    "xmlns:soapenv", "http://schemas.xmlsoap.org/soap/envelope");

When I create a new XmlElement using:

document.createElement("soapenv:Header");

...it doesn't include the soapenv namespace in the final XML. Any ideas why this happens?

More info:

Okay, I'll try to clarify this problem a bit. My code is:

XmlDocument document = new XmlDocument();
XmlElement element = document.CreateElement("foo:bar");
document.AppendChild(element); Console.WriteLine(document.OuterXml);

That outputs:

<bar />

However, what I want is:

<foo:bar />
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...