我需要创建一个 XmlDocument
,其根元素包含多个命名空间.我正在使用 C# 2.0 或 3.0
I need to create an XmlDocument
with a root element containing multiple namespaces. Am using C# 2.0 or 3.0
这是我的代码:
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("JOBS", "http://www.example.com");
doc.AppendChild(root);
XmlElement job = doc.CreateElement("JOB", "http://www.example.com");
root.AppendChild(job);
XmlElement docInputs = doc.CreateElement("JOB", "DOCINPUTS", "http://www.example.com");
job.AppendChild(docInputs);
XmlElement docInput = doc.CreateElement("JOB", "DOCINPUT", "http://www.example.com");
docInputs.AppendChild(docInput);
XmlElement docOutput = doc.CreateElement("JOB", "DOCOUTPUT", "http://www.example.com");
docOutputs.AppendChild(docOutput);
当前输出:
<JOBS xmlns="http://www.example.com">
<JOB>
<JOB:DOCINPUTS xmlns:JOB="http://www.example.com">
<JOB:DOCINPUT />
</JOB:DOCINPUTS>
<JOB:DOCOUTPUTS xmlns:JOB="http://www.example.com">
<JOB:DOCOUTPUT />
</JOB:DOCOUTPUTS>
</JOB>
</JOBS>
但是,我想要的输出是:
However, my desired output is:
<JOBS xmlns:JOBS="http://www.example.com" xmlns:JOB="http://www.example.com">
<JOB>
<JOB:DOCINPUTS>
<JOB:DOCINPUT />
</JOB:DOCINPUTS>
<JOB:DOCOUTPUTS>
<JOB:DOCOUTPUT />
</JOB:DOCOUTPUTS>
</JOB>
</JOBS>
我的问题:如何创建包含具有多个命名空间的根元素的 XmlDocument
?
My question: how do I create an XmlDocument
that contains a root element with multiple namespaces?
以下将生成您在上面请求的所需输出:
The following will generate the desired output that you requested above:
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("JOBS");
root.SetAttribute("xmlns:JOBS", "http://www.example.com");
root.SetAttribute("xmlns:JOB", "http://www.example.com");
doc.AppendChild(root);
XmlElement job = doc.CreateElement("JOB");
XmlElement docInputs = doc.CreateElement("JOB", "DOCINPUTS", "http://www.example.com");
XmlElement docInput = doc.CreateElement("JOB", "DOCINPUT", "http://www.example.com");
docInputs.AppendChild(docInput);
job.AppendChild(docInputs);
XmlElement docOutputs = doc.CreateElement("JOB", "DOCOUTPUTS", "http://www.example.com");
XmlElement docOutput = doc.CreateElement("JOB", "DOCOUTPUT", "http://www.example.com");
docOutputs.AppendChild(docOutput);
job.AppendChild(docOutputs);
doc.DocumentElement.AppendChild(job);
但是,在您的示例/所需输出中,对两个不同的前缀使用相同的 XML 命名空间似乎很奇怪.希望这会有所帮助.
However, it seems odd that in your example/desired output that the same XML namespace was used against two different prefixes. Hope this helps.
这篇关于如何使用 XmlDocument 向根元素添加多个命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!