如何使用 XmlSerializer 生成标签前缀 [英] How to generate tag prefixes using XmlSerializer

查看:28
本文介绍了如何使用 XmlSerializer 生成标签前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 XmlSerializer 生成以下内容:

I wanted to generate the following using XmlSerializer :

<atom:link href="http://dallas.example.com/rss.xml" rel="self" type="application/rss+xml" />

所以我尝试为我的元素添加一个命名空间:

So I tried to add a Namespace to my element :

[...]

    [XmlElement("link", Namespace="atom")]
    public AtomLink AtomLink { get; set; }

[...]

但输出是:

<link xmlns="atom" href="http://dallas.example.com/rss.xml" rel="self" type="application/rss+xml" />

那么生成前缀标签的正确方法是什么?

So what is the correct way to generate prefixed tags ?

推荐答案

首先,atom 命名空间通常是这样的:

First off, the atom namespace is normally this:

xmlns:atom="http://www.w3.org/2005/Atom"

为了让你的标签使用 atom 命名空间前缀,你需要用它来标记你的属性:

In order to get your tags to use the atom namespace prefix, you need to mark your properties with it:

[XmlElement("link", Namespace="http://www.w3.org/2005/Atom")]
public AtomLink AtomLink { get; set; }

您还需要告诉 XmlSerializer 使用它(感谢@Marc Gravell):

You also need tell the XmlSerializer to use it (thanks to @Marc Gravell):

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("atom", "http://www.w3.org/2005/Atom");
XmlSerializer xser = new XmlSerializer(typeof(MyType));
xser.Serialize(Console.Out, new MyType(), ns);

这篇关于如何使用 XmlSerializer 生成标签前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆