如何使用XmlDocument创建包含名称空间声明和带前缀名称的XML?

时间:2009-10-14 14:42:09

标签: xml xml-namespaces

我正在努力使用.NET中的XmlDocument对象输出以下XML。有什么建议吗?

这就是我想输出的内容......

<l:config
    xmlns:l="urn:LonminFRConfig"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="urn:LonminFRConfig lonminFRConfigSchema.xsd">

</l:config>

命名空间真的让我很难过!

2 个答案:

答案 0 :(得分:2)

试试这个:

XmlDocument xmlDoc = new XmlDocument();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("l", "urn:LonminFRConfig");
nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");

XmlElement config = xmlDoc.CreateElement("l:config", nsmgr.LookupNamespace("l"));
XmlAttribute schemaLocation = xmlDoc.CreateAttribute(
    "xsi:schemaLocation", nsmgr.LookupNamespace("xsi"));
config.Attributes.Append(schemaLocation);
schemaLocation.Value = "urn:LonminFRConfig lonminFRConfigSchema.xsd";

xmlDoc.AppendChild(config);
xmlDoc.Save(Console.Out);
祝你好运!

答案 1 :(得分:0)

你会这样做的。

const string lNS = "urn:lLominFRConfig";
const string xsiNS = "http://www.w3.org/2001/XMLSchema-instance";

var dom = new XmlDocument();

var configElem = dom.AppendChild(dom.CreateElement("l:config", lNS));

configElem.Attributes.Append(dom.CreateAttribute("xsi:schemaLocation", xsiNS))
    .Value = "urn:LonminFRConfig lonminFRConfigSchema.xsd";