c# - 您可以在运行时在 XmlRootAttribute 中设置 Namespace 字段吗?

标签 c# xml

基本上问题是我有一组存在于多个命名空间中的 XML 标记,但是因为 XML 命名空间是愚蠢的,这是不允许的,所以我需要在运行时根据数据的去向换出命名空间。

假设我有这个用于序列化/反序列化 XML 的类。

[System.Xml.Serialization.XmlRootAttribute(Namespace = "urn:foobar1")]
public class FooBar
{

    private string foo;

    public string Foo
    {
        get
        {
            return this.foo;
        }
        set
        {
            this.foo = value;
        }
    }
}

然后我使用 HttpClient 将其作为 XML 发送喜欢
HttpClient client=new HttpClient();
XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter()
{
    UseXmlSerializer = true
};

Foobar content=new FooBar(){Foo="content"};
client.PostAsync<FooBar>("https://my.endpoint.com", content, formatter);

它发送的 XML 是
<?xml version="1.0" encoding="utf-8"?>
<FooBar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:foobar1">
  <Foo>foobartest</Foo>
</FooBar>

有时这就是我需要的,但有时我需要完全相同的东西,除了它必须是 urn:foobar2而不是 urn:foobar1 .不幸的是XmlRootAttribute需要一个常量,所以我不能简单地传入不同的命名空间字符串。有没有一种替代方法可以让我在没有两个相同的 FooBar 的情况下做到这一点课?

最佳答案

如果删除 XmlRootAttribute , 您可以使用所需的命名空间实例化 XML 序列化程序并将其设置为格式化程序的序列化程序:

    string sNS = "urn:foobar2";
    HttpClient client = new HttpClient();
    XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter() { UseXmlSerializer = true };
    System.Xml.Serialization.XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(typeof(FooBar), sNS);
    formatter.SetSerializer(typeof(FooBar), xml);
    FooBar content = new FooBar() { Foo = "content" };
    client.PostAsync<FooBar>("https://my.endpoint.com", content, formatter);

这是它生成的 XML:

<?xml version="1.0" encoding="utf-16"?>
<FooBar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:foobar2">
  <Foo>content</Foo>
</FooBar>

关于c# - 您可以在运行时在 XmlRootAttribute 中设置 Namespace 字段吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61877651/

相关文章:

r - 使用 XML 和 Rvest 在 R 中进行网页抓取

c# - 可以在 Visual C# 中绘制 UML 图,然后从中生成代码吗?

c# - 'how to find us' 页面上的谷歌地图

c# - 我对 8-Puzzle 的 A* 搜索有什么问题?

c# - 创建一个可序列化的类 - 复杂对象

c# - XNA - 保存 xml 文件时出现 UnauthorizedAccessException

c# - 使用 Datapager 在 asp.net 中分页 - 下一个、上一个按钮

C# ListView排序

javascript - 如何将 HTML 文档作为起始值传递给 CodeMirror?

html - 带填充变量的 SVG 元素的 XPath?