C#对象到XML [英] C# object to XML

查看:280
本文介绍了C#对象到XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建这就要求C#对象转换为XML的应用程序。

I am creating an application which requires to convert c# object to XML.

我使用XML序列化类来实现这一目标。以下是代码片段:

I am using XML Serializer class to achieve this. Here is the code snippet:

public  class Anwer
{
    public int ID { get; set; }
    public string XML { get; set; }
    public Anwer(int ID, string XML)
    {
        this.ID = ID;
        this.XML = XML;
    }
    public Anwer() { }
}

下面的主要功能是:

   string AnswerXML = @"<Answer>1<Answer>";
   List<Anwer> answerList = new List<Anwer>();
   answerList.Add(new Anwer(1,AnswerXML));
   AnswerXML = @"<Answer>2<Answer>";
   answerList.Add(new Anwer(2, AnswerXML));
   XmlSerializer x = new XmlSerializer(answerList.GetType());
   x.Serialize(Console.Out, answerList);



输出是:

The output is:

<?xml version="1.0" encoding="IBM437"?>
<ArrayOfAnwer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="h
ttp://www.w3.org/2001/XMLSchema">
  <Anwer>
    <ID>1</ID>
    <XML>&lt;Answer&gt;1&lt;Answer&gt;</XML>
  </Anwer>
  <Anwer>
    <ID>2</ID>
    <XML>&lt;Answer&gt;2&lt;Answer&gt;</XML>
  </Anwer>
</ArrayOfAnwer>

在上面的代码'<'和'>'越来越被替换'<'和'和; GT';
如何避免这种情况?
我知道字符串替换是的方式之一,但我不希望使用它。

In the above code '<' and '>' are getting replaced by '<' and '&gt'; How to avoid this? I know string replace is one of the way, but I don't want to use it.

先谢谢了。

推荐答案

您不这样做,基本上是这样。这是正确的序列化对象 - XML序列化不希望有串搞乱东西内处理XML,所以适当地逃离了XML

You don't, basically. That's correctly serializing the object - the XML serializer doesn't want to have to deal with XML within strings messing things up, so it escapes the XML appropriately.

如果你反序列化在XML后,你会回到原来的对象数据。

If you deserialize the XML later, you'll get back to the original object data.

如果你想以定制方式来建立一个XML文档,我建议你不要'T使用XML序列化的开始。无论是使用LINQ到XML,如果你乐于创造内容等明确的,或者如果你的真的,真的的要包括直接在输出任意字符串,用的XmlWriter

If you're trying to build up an XML document in a custom fashion, I suggest you don't use XML serialization to start with. Either use LINQ to XML if you're happy to create elements etc explicitly, or if you really, really want to include arbitrary strings directly in your output, use XmlWriter.

如果你能给我们介绍一下你正在试图做更大的图片的更多信息,我们也许能够提出更好的替代品 - 建设XML字符串直接,几乎从来没有一个好主意。

If you could give us more information about the bigger picture of what you're trying to do, we may be able to suggest better alternatives - building XML strings directly is almost never a good idea.

这篇关于C#对象到XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆