【问题标题】:Xml element in xmlxml中的xml元素
【发布时间】:2017-02-06 07:28:28
【问题描述】:

我正在尝试创建包含另一个 xml 的 XML 文档。

所以首先我有对象 Foo 有一些属性。我用这个函数序列化它:

private static string SerializeToString(object dataToSerialize)
{
    var emptyNamepsaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
    var serializer = new XmlSerializer(dataToSerialize.GetType());
    var settings = new XmlWriterSettings
    {
        Indent = true,
        OmitXmlDeclaration = true
    };
    using (var stream = new StringWriter())
    using (var writer = XmlWriter.Create(stream, settings))
    {
        serializer.Serialize(writer, dataToSerialize, emptyNamepsaces);
        return stream.ToString();
    }
}

在我无权访问 Foo 类的另一个类中,我需要在 xml 文档中使用此 Foo 字符串保存一些数据。所以我有另一个像这样的对象:

public class Bar
{
    public int SomeInt { get; set; }

    public string FooString { get; set; }
}

当我序列化此 Bar 对象并将其保存为 xml 文档时。对于 FooString 元素,我得到了类似的东西。

<FooString>
        <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">&lt;Foo&gt;
  &lt;Guid&gt;2de0b223-308a-4c90-8dc7-09b48c1f42e6&lt;/Guid&gt;
  &lt;Id&gt;119&lt;/Id&gt;
  &lt;Name&gt;Some name&lt;/Name&gt;
  &lt;Description&gt;SomeDesc..&lt;/Description&gt;
&lt;/Foo&gt;</string>
  </FooString>

我知道这个 HTML 字符实体 (&amp;lt;) 存在,因为它保存为字符串。但是没有这个字符可以保存吗?但是我只像字符串一样保存它,因为我无法访问 Foo 类..所以我不知道它可能有什么参数..这就是为什么我将它保存为字符串并将其发送到 Bar 类。可以将其另存为其他内容,例如XmlElement 或者我不知道是什么...这也会在 Bar 序列化 xml 中显示 Foo 对象的结构??...谢谢!

【问题讨论】:

    标签: c# .net xml serialization xml-serialization


    【解决方案1】:

    在 xml 中包含 xml 的最佳方法是在您的类中包含 Foo 属性,而不是 FooString。如果您使用 xml 作为字符串,您无法确定它仍然是有效的 xml,它只是一个字符串。如果您不想或无法将 xml 序列化为数据,我建议将 Foo 序列化为CData,例如:

    public class Bar
    {
        public int SomeInt { get; set; }
    
        [XmlIgnore]
        public string FooString { get; set; }
        [XmlElement("FooString")]
        public XmlCDataSection FooStringCData
        {
            get { return new XmlDocument().CreateCDataSection(FooString); }
            set { FooString = (value != null) ? value.Data : null; }
        }
    }
    

    这会在 CData 部分中为您提供 xml + xml 字符串的输出:

    <Bar>
      <SomeInt>1</SomeInt>
      <FooString><![CDATA[<Z>
      <A>10</A>
      <B>12</B>
    </Z>]]></FooString>
    </Bar>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-06
      • 1970-01-01
      相关资源
      最近更新 更多