我想要一些通用方法将对象转换为xml节点:
如果我有这样的xml nodes
:
<BusinessObject xmlns="http://xmlns.oracle.com/bpm/bpmobject/Data/BusinessObject"><?xml version="1.0" encoding="utf-16"?>
<BusinessObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<attribute1>sss</attribute1>
<attribute2>sss</attribute2>
</BusinessObject></BusinessObject>
我将其转换为Json
,就像那样
{
"-xmlns": "http://xmlns.oracle.com/bpm/bpmobject/Data/BusinessObject",
"#text": "<?xml version=\"1.0\" encoding=\"utf-16\"?>
<BusinessObject xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
<attribute1>sss</attribute1>
<attribute2>sss</attribute2>
</BusinessObject>"
}
然后到c#class:
public class Rootobject
{
public string xmlns { get; set; }
public string text { get; set; }
}
现在如何在设置其值后再将其反转为xml节点?我想要一个不是这个例子的通用解决方案
答案 0 :(得分:1)
public class Rootobject
{
public string xmlns { get; set; }
public string text { get; set; }
}
public static void Main(string[] args)
{
Rootobject details = new Rootobject();
details.xmlns = "myNamespace";
details.text = "Value";
Serialize(details);
}
static public void Serialize(Rootobject details)
{
XmlSerializer serializer = new XmlSerializer(typeof(Rootobject));
using (TextWriter writer = new StreamWriter(@"C:\Xml.xml"))
{
serializer.Serialize(writer, details);
}
}
答案 1 :(得分:0)
您可以使用XML Serialization将Class
转换为XML
,反之亦然。
供参考,请阅读C# Tutorial - XML Serialization。
答案 2 :(得分:0)
示例:强>
[DataContract]
public class MyClass1 {
[DataMember]
public string name;
[DataMember]
public int age;
}
序列化/反序列化
MyClass1 obj = new MyClass1();
DataContractSerializer dcs = new DataContractSerializer(typeof(MyClass1));
using (Stream stream = new FileStream(@"C:\tmp\file.xml", FileMode.Create, FileAccess.Write))
{
using (XmlDictionaryWriter writer =
XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8))
{
writer.WriteStartDocument();
dcs.WriteObject(writer, obj);
}
}
答案 3 :(得分:0)
我认为您需要将Serializable属性应用于您的类才能序列化它。这可以确保您的类不使用某些无序列化属性。
[Serializable]
public class Rootobject
{
public string xmlns { get; set; }
public string text { get; set; }
}