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。谢谢,彼得
I have an XML file like:
<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>
With C# I create a new Item like:
XContainer container = XElement.Parse(xml);
XElement xmlTree =
new XElement("Item",
new XAttribute("Name", item.Name),
new XAttribute("Mode", item.Mode));
As you can see I don't add the "myPrefix" prefix. Can anyone tell me how i can do that? I don't want to declarde the xmlns again. Thanks, Peter
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编辑1:
如果您还将名称空间属性添加到元素,这将强制它添加前缀。但最终您仍然会在节点中得到 xmlns 属性。
要删除它,正如 Jeff 所说,您可能需要使用 XmlWriter。编辑 2:
要获得您想要的确切 XML,您还需要创建根元素:编辑 3:
好的。我找到了一种无需 XmlWriter 即可获得所需内容的方法:
编辑 4:
显然有一种更简单的方法...更简单...请参阅其他答案。
Edit 1:
If you add the namespace attribute aswell to the element this will force it to add the prefix. But you still end up with the xmlns attribute in the node.
To remove it you'll probably, as Jeff says, need to utilize XmlWriter.Edit 2:
To get the EXACT XML you want you need to create the root element aswell:Edit 3:
OK. I found a way to get what you want without XmlWriter:
Edit 4:
Apparently there was an easier way... a LOT easier... see the other answers.
您需要在命名空间中构造任何新元素。假设您知道 XML 示例中所需的命名空间的前缀,则按如下所示执行操作:
You need to construct any new elements in the namespace. Assuming you know the prefix of the namespace you want in the XML sample then do it as follows: