XElement仅添加前缀

Pet*_*ter 7 .net c# xml linq-to-xml

我有一个XML文件,如:

<myPrefix:Catalog xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
 xmlns:sys="clr-namespace:System;assembly=mscorlib" 
 xmlns:myPrefix="clr-namespace:........">

  <myPrefix:Item Name="Item1" Mode="All" />
  <myPrefix:Item Name="Item2" Mode="Single" />

</myPrefix:Catalog>
Run Code Online (Sandbox Code Playgroud)

使用C#我创建一个新项目,如:

XContainer container = XElement.Parse(xml);
XElement xmlTree = 
   new XElement("Item",
      new XAttribute("Name", item.Name),
      new XAttribute("Mode", item.Mode));
Run Code Online (Sandbox Code Playgroud)

如您所见,我不添加"myPrefix"前缀.谁能告诉我怎么能这样做?我不想再声明xmlns.谢谢,彼得

Tom*_*ers 8

    XElement container = XElement.Parse(xml);
    XNamespace myPrefix = container.GetNamespaceOfPrefix("myPrefix");

    XElement xmlTree = new XElement(myPrefix + "Item",     
                            new XAttribute("Name", item.Name), 
                            new XAttribute("Mode", item.Mode));

    container.Add(xmlTree);
Run Code Online (Sandbox Code Playgroud)


San*_*nen 4

编辑 1:
如果将命名空间属性也添加到元素中,这将强制它添加前缀。但最终您仍然会在节点中得到 xmlns 属性。正如 Jeff 所说,要删除它,您可能需要使用 XmlWriter。

编辑 2:
要获取所需的确切 XML,您还需要创建根元素:

编辑3:
好的。我找到了一种无需 XmlWriter 即可获得所需内容的方法:

var xml = "<myPrefix:Catalog xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" xmlns:sys=\"clr-namespace:System;assembly=mscorlib\" xmlns:myPrefix=\"clr-namespace:........\"><myPrefix:Item Name=\"Item1\" Mode=\"All\" /></myPrefix:Catalog>";

XNamespace presentation = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
XNamespace xaml = "http://schemas.microsoft.com/winfx/2006/xaml";
XNamespace mscorlib = "clr-namespace:System;assembly=mscorlib";
XNamespace myPrefix = "clr-namespace:.......";

XElement container = XElement.Parse(xml);

var xmlTree = new XElement("Item",
               new XAttribute("Name", "Item2"),
               new XAttribute("Mode", "Single"));

container.Add(xmlTree);

foreach (var el in container.DescendantsAndSelf())
{
  el.Name = myPrefix.GetName(el.Name.LocalName);
  var atList = el.Attributes().ToList();
  el.Attributes().Remove();
  foreach (var at in atList)
  {
    if (el.Name.LocalName == "Catalog" && at.Name.LocalName != "xmlns")
      continue;
    el.Add(new XAttribute(at.Name.LocalName, at.Value));
  }
}

container.Add(new XAttribute(XNamespace.Xmlns + "x", xaml));
container.Add(new XAttribute(XNamespace.Xmlns + "sys", mscorlib));
container.Add(new XAttribute(XNamespace.Xmlns + "myPrefix", myPrefix));
Run Code Online (Sandbox Code Playgroud)

编辑4:
显然有一个更简单的方法...更简单...请参阅其他答案。