如何使用 XMLSerializer 添加没有前缀的默认命名空间
我正在尝试使用 XmlSerializer
生成一个包含默认命名空间且没有前缀的 XML 文档,例如
<?xml version="1.0" encoding="utf-8" ?>
<MyRecord ID="9266" xmlns="http://www.website.com/MyRecord">
<List>
<SpecificItem>
使用以下代码...
string xmlizedString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(ExportMyRecord));
XmlSerializerNamespaces xmlnsEmpty = new XmlSerializerNamespaces();
xmlnsEmpty.Add(string.Empty, string.Empty);
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, myRecord, xmlnsEmpty);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
xmlizedString = this.UTF8ByteArrayToString(memoryStream.ToArray());
和类结构...
[Serializable]
[XmlRoot("MyRecord")]
public class ExportMyRecord
{
[XmlAttribute("ID")]
public int ID { get; set; }
现在,我尝试了各种选项.. .
XmlSerializer xs = new XmlSerializer
(typeof(ExportMyRecord),"http://www.website.com/MyRecord");
或 ...
[XmlRoot(Namespace = "http://www.website.com/MyRecord", ElementName="MyRecord")]
给我...
<?xml version="1.0" encoding="utf-8"?>
<q1:MylRecord ID="9266" xmlns:q1="http://www.website.com/MyRecord">
<q1:List>
<q1:SpecificItem>
我需要 XML 具有不带前缀的命名空间,因为它将发送给第三方提供商,并且他们拒绝所有其他替代方案。
I am trying to generate an XML document that contains the default namespace without a prefix using XmlSerializer
, e.g.
<?xml version="1.0" encoding="utf-8" ?>
<MyRecord ID="9266" xmlns="http://www.website.com/MyRecord">
<List>
<SpecificItem>
Using the following code ...
string xmlizedString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(ExportMyRecord));
XmlSerializerNamespaces xmlnsEmpty = new XmlSerializerNamespaces();
xmlnsEmpty.Add(string.Empty, string.Empty);
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, myRecord, xmlnsEmpty);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
xmlizedString = this.UTF8ByteArrayToString(memoryStream.ToArray());
and class structure ...
[Serializable]
[XmlRoot("MyRecord")]
public class ExportMyRecord
{
[XmlAttribute("ID")]
public int ID { get; set; }
Now, I've tried various options ...
XmlSerializer xs = new XmlSerializer
(typeof(ExportMyRecord),"http://www.website.com/MyRecord");
or ...
[XmlRoot(Namespace = "http://www.website.com/MyRecord", ElementName="MyRecord")]
gives me ...
<?xml version="1.0" encoding="utf-8"?>
<q1:MylRecord ID="9266" xmlns:q1="http://www.website.com/MyRecord">
<q1:List>
<q1:SpecificItem>
I need the XML to have the namespace without the prefix as it's going to a third party provider and they reject all other alternatives.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就这样:
There you go:
这是可用于任何类型的通用实现:
Here's a generic implementation that can be used for any type: