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

查看:189
本文介绍了使用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 />

推荐答案

您可以使用 示例:

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

预期输出:

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

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

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