C# XmlSerializer.Serialize 剥离 <xml> 标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10218181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:56:09  来源:igfitidea点击:

XmlSerializer.Serialize Stripping the <xml> tag

c#

提问by Mike Wills

I am trying to get communicate to a payment processor. When I use XmlSerializer.Serializeon my object I get

我正在尝试与支付处理器进行通信。当我XmlSerializer.Serialize在我的对象上使用时,我得到

<?xml version=\"1.0\" encoding=\"utf-16\"?>
<txn xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
  <ssl_merchant_id>xxxxxx</ssl_merchant_id>
  <ssl_user_id>xxxxxx</ssl_user_id>
  <ssl_pin>xxxxxx</ssl_pin>
  <ssl_test_mode>True</ssl_test_mode>
  <ssl_transaction_type>ccavsonly</ssl_transaction_type>
  <ssl_card_number>4111111111111111</ssl_card_number>
  <ssl_exp_date>0612</ssl_exp_date>
  <ssl_avs_address>101 Main St.</ssl_avs_address>
  <ssl_avs_zip>90210</ssl_avs_zip>
</txn>

Prior to using that method, I manually built the XML for testing and this worked:

在使用该方法之前,我手动构建了用于测试的 XML,这有效:

<txn>
  <ssl_merchant_id>xxxxxx</ssl_merchant_id>
  <ssl_user_id>xxxxxx</ssl_user_id>
  <ssl_pin>xxxxxx</ssl_pin>
  <ssl_test_mode>True</ssl_test_mode>
  <ssl_transaction_type>ccavsonly</ssl_transaction_type>
  <ssl_card_number>4111111111111111</ssl_card_number>
  <ssl_exp_date>0612</ssl_exp_date>
  <ssl_avs_address>101 Main St.</ssl_avs_address>
  <ssl_avs_zip>90210</ssl_avs_zip>
</txn>

How would I go about stripping out the <?xml version=\"1.0\" encoding=\"utf-16\"?>and xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">from the XML or not have the serializer generate it to begin with?

我将如何从 XML 中剥离<?xml version=\"1.0\" encoding=\"utf-16\"?>xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">或者不让序列化程序生成它?

My object looks like:

我的对象看起来像:

[XmlRoot(ElementName="txn")]
public class AvsTransmission
{
    [XmlElement]
    public string ssl_merchant_id { get; set; }
    [XmlElement]
    public string ssl_user_id { get; set; }
    [XmlElement]
    public string ssl_pin { get; set; }
    [XmlElement]
    public string ssl_test_mode { get; set; }
    [XmlElement]
    public string ssl_transaction_type { get; set; }
    [XmlElement]
    public string ssl_card_number { get; set; }
    [XmlElement]
    public string ssl_exp_date { get; set; }
    [XmlElement]
    public string ssl_avs_address { get; set; }
    [XmlElement]
    public string ssl_avs_zip { get; set; }
}

采纳答案by payo

My first answer was only half of the problem, you also have to remove the declaration as has been mentioned.

我的第一个答案只是问题的一半,您还必须删除前面提到的声明。

Here is an example:

下面是一个例子:

XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;

MemoryStream ms = new MemoryStream();
XmlWriter writer = XmlWriter.Create(ms, settings);

XmlSerializerNamespaces names = new XmlSerializerNamespaces();
names.Add("", "");

XmlSerializer cs = new XmlSerializer(typeof(Cat));

cs.Serialize(writer, new Cat { Lives = 9 }, names);

ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms);
var xml = sr.ReadToEnd();

The string xmlnow contains:

该字符串xml现在包含:

<cat><Lives>9</Lives></cat>

回答by mafue

If you use XmlWriter there is a setting to omit the declaration http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.omitxmldeclaration.aspx

如果您使用 XmlWriter,则有一个设置可以省略声明 http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.omitxmldeclaration.aspx

I'll work on an example, but that might be enough to get you going.

我会做一个例子,但这可能足以让你继续前进。



EDIT: Here's a sample that runs in LinqPad

编辑:这是在 LinqPad 中运行的示例

string test  = "test";
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
MemoryStream strm = new MemoryStream();
XmlWriter writer = XmlWriter.Create(strm, settings);
XmlSerializer serializer =  new XmlSerializer(typeof(string));
serializer.Serialize(writer, test);
strm.Position = 0;
StreamReader reader = new StreamReader(strm);
var x = reader.ReadToEnd();
x.Dump();
writer.Close();
reader.Close();
strm.Close();

Output

输出

<string>test</string>

<string>test</string>

Comment out line 3 and the Output is

注释掉第 3 行,输出是

<?xml version="1.0" encoding="utf-8"?><string>test</string>

<?xml version="1.0" encoding="utf-8"?><string>test</string>

回答by user3652716

Just to simplify the soln. of the original problem of removing UTF encoding declaration here is the code

只是为了简化解决方案。这里删除UTF编码声明的原始问题是代码

                StringBuilder sb = new StringBuilder();
                var serializer = new System.Xml.Serialization.XmlSerializer(typeToSerialize.GetType());
                serializer.Serialize(System.Xml.XmlWriter.Create(sb, new System.Xml.XmlWriterSettings { OmitXmlDeclaration = true, Indent=true }), typeToSerialize);

回答by Doctor

First function convert object to xml string, the second one convert object and write xml to file simultaneously.

第一个函数将对象转换为 xml 字符串,第二个函数同时转换对象并将 xml 写入文件。

    public static string Serialize<T>(T obj)
    {
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.OmitXmlDeclaration = true;
        var writer = new StringWriter();
        XmlWriter xmlWriter = XmlWriter.Create(writer, settings);

        XmlSerializerNamespaces names = new XmlSerializerNamespaces();
        names.Add("", "");

        XmlSerializer serializer = new XmlSerializer(typeof(T));

        serializer.Serialize(xmlWriter, obj, names);
        var xml = writer.ToString();
        return xml;
    }

    public static void Serialize<T>(T obj, string filepath)
    {
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.OmitXmlDeclaration = true;
        var writer = new StreamWriter(filepath);
        XmlWriter xmlWriter = XmlWriter.Create(writer, settings);

        XmlSerializerNamespaces names = new XmlSerializerNamespaces();
        names.Add("", "");

        XmlSerializer serializer = new XmlSerializer(typeof(T));

        serializer.Serialize(xmlWriter, obj, names);
    }

Actually I realized that code repeat yourself. In these methods, change only one thing which is writer object, so the code must be like below. In these way, you can easily use code just by changing writer object type.

实际上我意识到代码重复了自己。在这些方法中,只更改了编写器对象的一件事,因此代码必须如下所示。通过这些方式,您只需更改编写器对象类型即可轻松使用代码。

    public static string Serialize<T>(T obj)
    {
        var writer = new StringWriter();
        Serialize<T>(obj,writer);
        var xml = writer.ToString();
        return xml;
    }

    public static void Serialize<T>(T obj, string filepath)
    {
        var writer = new StreamWriter(filepath);
        Serialize<T>(obj,writer);
    }

    public static void Serialize<T>(T obj, TextWriter writer)
    {
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.OmitXmlDeclaration = true;
        XmlWriter xmlWriter = XmlWriter.Create(writer, settings);            
        XmlSerializerNamespaces names = new XmlSerializerNamespaces();
        names.Add("", "");            
        XmlSerializer serializer = new XmlSerializer(typeof(T));            
        serializer.Serialize(xmlWriter, obj, names);
    }

回答by D34th

Very similar to @payo's orignal answer:

与@payo 的原始答案非常相似:

If you want to remove the namespace you may also want to remove the version, to save you searching I've added that functionality so the below code will do both.

如果您想删除命名空间,您可能还想删除版本,为了节省您的搜索时间,我添加了该功能,因此下面的代码将同时执行这两项操作。

I've also wrapped it in a generic method as I'm creating very large xml files which are too large to serialize in memory so I've broken my output file down and serialize it in smaller "chunks":

我还用通用方法将它包装起来,因为我正在创建非常大的 xml 文件,这些文件太大而无法在内存中进行序列化,因此我将输出文件分解并将其序列化为较小的“块”:

public string XmlSerialize<T>(T entity) where T : class
{
    // removes version
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.OmitXmlDeclaration = true;

    XmlSerializer xsSubmit = new XmlSerializer(typeof(T));
    StringWriter sw = new StringWriter();
    using (XmlWriter writer = XmlWriter.Create(sw, settings))
    {
        // removes namespace
        var xmlns = new XmlSerializerNamespaces();
        xmlns.Add(string.Empty, string.Empty);

        xsSubmit.Serialize(writer, entity, xmlns);
        return sw.ToString(); // Your XML
    }
}