0

我正在尝试将 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>
4

1 回答 1

2

如果你想得到一个XElement,这xml.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>
于 2013-07-10T08:41:19.070 回答