我正在尝试使用 C# 和 .NET(版本 2.0.. 是的,版本 2.0)创建一个
XmlDocument
。我已经使用以下方法设置了命名空间属性:
document.DocumentElement.SetAttribute(
"xmlns:soapenv", "http://schemas.xmlsoap.org/soap/envelope");
当我使用以下方法创建新的
XmlElement
时:
document.createElement("soapenv:Header");
...最终的 XML 中不包含
soapenv
命名空间。有什么想法为什么会发生这种情况吗?
更多信息:
好吧,我会尽力澄清一下这个问题。我的代码是:
XmlDocument document = new XmlDocument();
XmlElement element = document.CreateElement("foo:bar");
document.AppendChild(element); Console.WriteLine(document.OuterXml);
输出:
<bar />
但是,我想要的是:
<foo:bar />
您可以使用
XmlDocument.CreateElement 方法(String、String、String)为
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);
预期输出#1:
<foo:bar xmlns:foo="http://tempuri.org/foo" />
要获得更有趣的示例,请在
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>
请注意,子元素
bizz
和 buzz
以命名空间前缀 foo
为前缀,并且命名空间 URI http://tempuri.org/foo
不会在子元素上重复,因为它是在父元素 bar
中定义的.
使用系统; 使用 System.Xml;
命名空间 ConsoleApp3 { 班级计划 { 静态无效主(字符串[]参数) { var Ruta = @"C:\Users\isaac\Documents\XML\XMLTEST.xml"; 阿格雷加(鲁塔,“32323”);
}
public static void Agregar(string Ruta, string valor)
{
XmlDocument XML = new XmlDocument();
XML.Load(Ruta);
XmlNode root = XML.GetElementsByTagName("dte:DatosEmision")[0];
string dte = "http://www.sat.gob.gt/dte/fel/0.2.0";
XmlElement childElement = XML.CreateElement("dte", "Otros", dte);
XmlElement childElement1 = XML.CreateElement("dte", "OtroTexto", dte);
childElement1.SetAttribute("codigo", "OC");
childElement1.InnerText = valor;
////
childElement.AppendChild(childElement1);
try
{
root.InsertAfter(childElement, root.LastChild);
}
catch (Exception x)
{
Console.WriteLine(x);
}
XML.Save("XMLFile2.xml");
}
}
}
也许您可以分享您所期望的最终 XML 文档。
但是据我了解,你想要做的事情看起来像:
<?xml version="1.0"?>
<soapMessage xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope">
<Header xmlns="http://schemas.xmlsoap.org/soap/envelope" />
</soapMessage>
所以执行此操作的代码是:
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));