如何从类型为T的对象获取xml节点?

时间:2013-07-10 07:54:10

标签: c# xml-serialization xmlnode

我正在尝试将类型T的对象转换为xml节点,因为我想在wpf控件中显示xml节点。下面是linqpad片段,我正在使用:

[Serializable]
public class test {
public int int1  { get ; set ;}
public int int2 { get ; set ;} 
public string str1 { get ; set ;}
}

void Main()
{
test t1 = new test () ;
t1.int1 = 12 ;
t1.int2 = 23 ;
t1.str1 = "hello" ;


System.Xml.Serialization.XmlSerializer x = new  System.Xml.Serialization.XmlSerializer(t1.GetType());
StringWriter sww = new StringWriter();
 XmlWriter writer = XmlWriter.Create(sww);
 x.Serialize(writer, t1);
 var xml = sww.XmlSerializeToXElement (); 
 xml.Dump () ;

}

我没有得到预期的结果而是,我得到了这个:

<StringWriter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <NewLine>
</NewLine>
</StringWriter>

1 个答案:

答案 0 :(得分:2)

如果您想获得XElementxml.Root就是您想要的:

System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(t1.GetType());
StringWriter sww = new StringWriter();
XmlWriter writer = XmlWriter.Create(sww);
x.Serialize(writer, t1);
var xml = XDocument.Parse(sww.ToString());
Console.WriteLine(xml.Root);

输出:

<test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <int1>12</int1>
  <int2>23</int2>
  <str1>hello</str1>
</test>