Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 序列化并返回原始xml_C#_Xml_Serialization - Fatal编程技术网

C# 序列化并返回原始xml

C# 序列化并返回原始xml,c#,xml,serialization,C#,Xml,Serialization,我正在使用XmlSerializer将对象序列化为xml。在对象被序列化之后,我会得到如下结果 <?xml version="1.0" encoding="utf-8"?> <xml xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> </xml> 在C#中,您可以执行以下操作: XmlSerializer se

我正在使用XmlSerializer将对象序列化为xml。在对象被序列化之后,我会得到如下结果

<?xml version="1.0" encoding="utf-8"?>
<xml xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</xml>
在C#中,您可以执行以下操作:

XmlSerializer serializer = new XmlSerializer(typeof(object));
StringWriter stringWriter = new StringWriter();

using (XmlWriter writer = XmlWriter.Create(stringWriter, new XmlWriterSettings() { OmitXmlDeclaration = true }))
{
    serializer.Serialize(writer, this, new XmlSerializerNamespaces() { "",""});
}
string xmlText = stringWriter.ToString();
说明:

ommitXMLDeclaration=true
使其删除声明


new XmlSerializerNamespaces(){“,”}
删除名称空间。

什么语言:C#,Java?谢谢提示。我以为它会工作,但当使用空名称空间时,我会出错。然后,我在MSDN上查看了这一点,并看到“不支持创建空名称空间和前缀对”,因此我想我需要编写一个自定义序列化程序或找到一个第三方库来完成这一工作。我真的很感激你的回答!它让我接近了!根据这一点(以及其他一些),这似乎是可行的:
XmlSerializerNamespaces ns=newxmlserializernamespaces();加上(“,”)是的,我终于能够让它工作了。我用我正在使用的代码编辑了我的原始帖子。谢谢你的帮助。
    public static string Serialize(object o)
    {
        XmlWriterSettings xws = new XmlWriterSettings();
        xws.OmitXmlDeclaration = true;
        xws.Indent = true;

        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add(String.Empty, String.Empty);

        StringBuilder sb = new StringBuilder();
        XmlWriter xmlw = XmlWriter.Create(sb, xws);
        XmlSerializer serializer = new XmlSerializer(o.GetType());
        serializer.Serialize(xmlw, o, ns);
        xmlw.Flush();

        return sb.ToString();
    }
XmlSerializer serializer = new XmlSerializer(typeof(object));
StringWriter stringWriter = new StringWriter();

using (XmlWriter writer = XmlWriter.Create(stringWriter, new XmlWriterSettings() { OmitXmlDeclaration = true }))
{
    serializer.Serialize(writer, this, new XmlSerializerNamespaces() { "",""});
}
string xmlText = stringWriter.ToString();