使用 XmlDocument.CreateElement() 创建具有命名空间的 XML 元素 [英] Creating an XML element with a namespace with XmlDocument.CreateElement()

查看:50
本文介绍了使用 XmlDocument.CreateElement() 创建具有命名空间的 XML 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 C# 和 .NET(版本 2.0.. 是的,版本 2.0)创建一个 XmlDocument.我已使用以下方法设置命名空间属性:

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

当我创建一个新的 XmlElement 使用:

When I create a new XmlElement using:

document.createElement("soapenv:Header");

...它不包括最终 XML 中的 soapenv 命名空间.任何想法为什么会发生这种情况?

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

更多信息:

好的,我会试着澄清一下这个问题.我的代码是:

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

输出:

<bar />

但是,我想要的是:

<foo:bar />

推荐答案

您可以使用 XmlDocument.CreateElement 方法(字符串、字符串、字符串)

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

示例:

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

预期输出 #1:

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

举个更有趣的例子,在 document.AppendChild(element); 之前插入这些语句:

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

预期输出 #2:

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

请注意,子元素 bizzbuzz 以命名空间前缀 foo 为前缀,命名空间 URI http://tempuri.org/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.

这篇关于使用 XmlDocument.CreateElement() 创建具有命名空间的 XML 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆