gpt4 book ai didi

c# - 从 XPathNavigator.AppendChild() 创建时如何设置 XmlWriter.XmlWriterSettings?

转载 作者:行者123 更新时间:2023-11-30 15:05:14 27 4
gpt4 key购买 nike

我需要将 XmlWriter 的 XmlWriterSettings 的 OmitXmlDeclaration 属性设置为 false 以不创建 XML 声明。问题是我通过调用 XPathNavigator.AppendChild() 方法创建了 XmlWriter。代码如下:

    public String GetEntityXml<T>(List<T> entities)
{
XmlDocument xmlDoc = new XmlDocument();
XPathNavigator nav = xmlDoc.CreateNavigator();

using (XmlWriter writer = nav.AppendChild())
{

XmlSerializer ser = new XmlSerializer(typeof(List<T>), new XmlRootAttribute(typeof(T).Name + "_LIST"));
ser.Serialize(writer, entities);
}

StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);

xmlDoc.WriteTo(xmlTextWriter);

string resultString = stringWriter.ToString();

stringWriter.Close();
xmlTextWriter.Close();

return resultString;
}

知道如何序列化 List 而没有 XML 声明吗?

最佳答案

当我执行你的代码时,我没有得到 XML 声明。序列化 List<int>给我:

<Int32_LIST xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<int>5</int>
<int>7</int>
<int>2</int>
</Int32_LIST>

请注意 OmitXmlDeclaration 的“XML 声明”指的是通常类似于:

<?xml version="1.0" encoding="UTF-8" ?>

如果您指的是 xmlns部分,那么这些被称为“XML namespace declarations”,并且可以通过初始化 XmlSerializerNamespaces 来消除。具有默认空 namespace 的实例,并将其传递给您的 Serialize方法:

XmlSerializer ser = new XmlSerializer(typeof(List<T>), new XmlRootAttribute(typeof(T).Name + "_LIST"));
var namespaces = new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") });
ser.Serialize(writer, entities, namespaces);

下面是一个缩短的实现,它实现了与您的代码相同的结果:

public String GetEntityXml<T>(List<T> entities)
{
var sb = new StringBuilder();
var settings = new XmlWriterSettings { OmitXmlDeclaration = true };
using (XmlWriter writer = XmlWriter.Create(sb, settings))
{
XmlSerializer ser = new XmlSerializer(typeof(List<T>), new XmlRootAttribute(typeof(T).Name + "_LIST"));
var namespaces = new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") });
ser.Serialize(writer, entities, namespaces);
}
return sb.ToString();
}

关于c# - 从 XPathNavigator.AppendChild() 创建时如何设置 XmlWriter.XmlWriterSettings?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9232060/

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