微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – XElement仅添加前缀

我有一个 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>

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

XContainer container = XElement.Parse(xml);
XElement xmlTree = 
   new XElement("Item",new XAttribute("Name",item.Name),new XAttribute("Mode",item.Mode));

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

解决方法

编辑1:
如果您将namespace属性以及元素添加到元素中,则会强制它添加前缀.但是您仍然在节点中使用xmlns属性.要删除它,您可能正如杰夫所说,需要使用XmlWriter.

编辑2:
要获得您想要的EXACT 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","Item2"),"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));

编辑4:显然有一种更简单的方法…更容易…看到其他答案.

原文地址:https://www.jb51.cc/csharp/100451.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐