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

本文关键字:获取 xml 节点 对象 类型 | 更新日期: 2023-09-27 18:21:42

我正试图将类型为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>

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

如果您正试图获得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>
相关文章: