如何使用linq xml将命名空间添加到xml

问题更新:如果我的问题不明确,我很抱歉

这是现在使用的代码

XDocument doc = XDocument.Parse(framedoc.ToString()); foreach (var node in doc.Descendants("document").ToList()) { XNamespace ns = "xsi"; node.SetAttributeValue(ns + "schema", ""); node.Name = "alto"; } 

这是输出

  

我的目标是这样的

 xsi:schemaLocation="" 

p1xmlns:p1="xsi"来自哪里?

当你写作

 XNamespace ns = "xsi"; 

那就是创建一个URI只有“xsi”的XNamespace 。 那不是你想要的。 您需要xsi的名称空间别名 …通过xmlns属性使用适当的URI。 所以你要:

 XDocument doc = XDocument.Parse(framedoc.ToString()); foreach (var node in doc.Descendants("document").ToList()) { XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance"; node.SetAttributeValue(XNamespace.Xmnls + "xsi", ns.NamespaceName); node.SetAttributeValue(ns + "schema", ""); node.Name = "alto"; } 

或者更好的是,只需在根元素处设置别名:

 XDocument doc = XDocument.Parse(framedoc.ToString()); XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance"; doc.Root.SetAttributeValue(XNamespace.Xmlns + "xsi", ns.NamespaceName); foreach (var node in doc.Descendants("document").ToList()) { node.SetAttributeValue(ns + "schema", ""); node.Name = "alto"; } 

创建文档的示例:

 using System; using System.Xml.Linq; public class Test { static void Main() { XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance"; XDocument doc = new XDocument( new XElement("root", new XAttribute(XNamespace.Xmlns + "xsi", ns.NamespaceName), new XElement("element1", new XAttribute(ns + "schema", "s1")), new XElement("element2", new XAttribute(ns + "schema", "s2")) ) ); Console.WriteLine(doc); } } 

输出: