2009-10-14 77 views

回答

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

祝你好运!

+0

LookupNamespace是相当昂贵的,当你需要创建很多特别是从头开始,你已经知道你要使用的别名和命名空间创建时的元素。 – AnthonyWJones 2009-10-14 15:00:37

+0

@AnthonyWJones:ty为您的信息!我只是通过反射器阅读LookupNamespace实现,并且在内部使用Dictionary <>,所以这很快,但不会比const字符串快,当然=) – 2009-10-14 15:11:43

+0

这就像一个魅力,感谢鲁本斯! – willem 2009-10-14 15:16:19

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"; 
+0

-1:安东尼,我不相信这会发出命名空间声明。 – 2009-10-14 15:02:38

+0

@John:实际上,它的确如此; nsmgr.LookupNamespace()方法返回一个字符串,所以这段代码非常相当于我的 – 2009-10-14 15:06:37

+0

@John:你是否先试试?我做到了。 – AnthonyWJones 2009-10-14 15:17:09

相关问题