代码之家  ›  专栏  ›  技术社区  ›  Ben Hymers

如何使xmlserialiser不以<开头?XML?>?

  •  1
  • Ben Hymers  · 技术社区  · 16 年前

    我正在使用的文件格式(ofx)类似于xml,并且在类似xml的位开始之前包含一堆纯文本内容。不过,它不喜欢在纯文本和xml部分之间使用,所以我想知道是否有办法让xmlserialiser忽略这一点。我知道我可以浏览一下文件并删除这一行,但如果不首先写它,会更简单、更干净!有什么想法吗?

    2 回复  |  直到 16 年前
        1
  •  4
  •   Philip Rieck    16 年前

    不太难,只需序列化为显式声明的xmlwriter,并在序列化之前设置该writer上的选项。

    public static string SerializeExplicit(SomeObject obj)
    {    
        XmlWriterSettings settings;
        settings = new XmlWriterSettings();
        settings.OmitXmlDeclaration = true;
    
        XmlSerializerNamespaces ns;
        ns = new XmlSerializerNamespaces();
        ns.Add("", "");
    
    
        XmlSerializer serializer;
        serializer = new XmlSerializer(typeof(SomeObject));
    
        //Or, you can pass a stream in to this function and serialize to it.
        // or a file, or whatever - this just returns the string for demo purposes.
        StringBuilder sb = new StringBuilder();
        using(var xwriter = XmlWriter.Create(sb, settings))
        {
    
            serializer.Serialize(xwriter, obj, ns);
            return sb.ToString();
        }
    }
    
        2
  •  6
  •   Welbog    16 年前

    在调用 Serialize 方法。它的 Settings 财产有 OmitXmlDeclaration 属性,您将要将其设置为true。你还需要设置 ConformanceLevel 属性,否则XmlWriter将忽略 省略xmlDeclaration 财产。

    XmlWriterSettings settings = new XmlWriterSettings();
    settings.OmitXmlDeclaration = true;
    settings.ConformanceLevel = ConformanceLevel.Fragment;
    XmlWriter writer = XmlWriter.Create(/*whatever stream you need*/,settings);
    serializer.Serialize(writer,objectToSerialize);
    writer.close();