c# – XElement仅添加前缀
发布时间:2020-12-15 17:13:18 所属栏目:百科 来源:网络整理
导读:我有一个 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-namespac
我有一个
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: 编辑3: 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:显然有一种更简单的方法…更容易…看到其他答案. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |