gpt4 book ai didi

c# - XmlSerializer 生成没有命名空间前缀的 XML

转载 作者:太空狗 更新时间:2023-10-29 20:57:42 26 4
gpt4 key购买 nike

我必须创建一个包含所有元素前缀的 XML 文件,如下所示:

<ps:Request num="123" xmlns:ps="www.ladieda.com">
<ps:ClientId>5566</ps:ClientId>
<ps:Request>

当我序列化我的对象时,c# 很聪明,它会这样做:

<Request num="123" xmlns="www.ladieda.com">
<ClientId>5566</ClientId>
<Request>

这很好,因为 ps: 不是必需的。

但有没有办法强制 C# 序列化所有前缀?

我的序列化代码是这样的(对于传入对象 pObject):

String XmlizedString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(pObject.GetType());
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

xs.Serialize(xmlTextWriter, pObject);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
return XmlizedString;


private String UTF8ByteArrayToString(Byte[] characters)
{
UTF8Encoding encoding = new UTF8Encoding();
String constructedString = encoding.GetString(characters);
return (constructedString);
}

最佳答案

首先,如果您的字符串的使用者正在处理 XML,那么他们不会关心前缀,因为它(对于 XML)无关紧要。也许他们不理解 XML,并认为他们正在处理一个字符串(可能需要在每个元素上都有字符串“ps:”)。

其次,您应该稍微更改一下代码:

XmlSerializer xs = new XmlSerializer(pObject.GetType());
using (MemoryStream memoryStream = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings()
{
Encoding = Encoding.UTF8
};
using (XmlWriter writer = XmlWriter.Create(memoryStream, settings))
{
xs.Serialize(writer, pObject);
}
return Encoding.UTF8.GetString(memoryStream.ToArray());
}

如果抛出异常,这将正确处理流和 XmlWriter,停止使用已弃用的 XmlTextWriter 类,但仍返回包含为 UTF-8 编写的 XML 的字符串。

最后,要控制前缀,参见"How to: Qualify XML Element and XML Attribute Names" :

XmlSerializerNamespaces myNamespaces = new XmlSerializerNamespaces();
myNamespaces.Add("ps", "www.ladieda.com");

XmlSerializer xs = new XmlSerializer(pObject.GetType());
using (MemoryStream memoryStream = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings()
{
Encoding = Encoding.UTF8
};
using (XmlWriter writer = XmlWriter.Create(memoryStream, settings))
{
xs.Serialize(writer, pObject, myNamespaces);
}
return Encoding.UTF8.GetString(memoryStream.ToArray());
}

关于c# - XmlSerializer 生成没有命名空间前缀的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2837022/

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