gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 09:58:25 28 4
gpt4 key购买 nike

基本上问题是我有一组存在于多个命名空间中的 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com