public class Item
{
public string name {get;set;}
public string code {get;set;}
}
Item item=new Item{name="bd",code="001"}
I want to make item object to the xml as like the following example:
<Item>
<p1:name url="https://t1.com"> bd</name>
<p2:code url="https://t2.com">0001</code>
</Item>
Try following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
Item item = new Item()
{
name = new URL() { url = "https://t1.com", value = "bd" },
code = new URL() { url = "https://t2.com", value = "0001" }
};
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create(FILENAME, settings);
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add("p1", "MyURL1");
namespaces.Add("p2", "MyURL2");
XmlSerializer serializer = new XmlSerializer(typeof(Item));
serializer.Serialize(writer, item, namespaces);
}
}
public class Item
{
[XmlElement(Namespace = "MyURL1")]
public URL name { get; set; }
[XmlElement(Namespace = "MyURL2")]
public URL code { get; set; }
}
public class URL
{
[XmlAttribute()]
public string url { get; set;}
[XmlText]
public string value { get; set;}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.