使用c创建XML的问题#
问题描述:
我正在寻找通过xml序列化创建xml的连击解决方案。我需要什么,我有这样的使用c创建XML的问题#
<product Id="1">
<name>2 1/2 X 6 PVC NIPPLE TOE SCH 80</name>
<notes>
<note>!--note 1---</note>
<note>!--note 2--</note>
......
</notes>
</product>
给定的格式我在做什么在这里,我创造了这样
public class product
{
[XmlElement("name")]
public string Name { get; set; }
[XmlArray("notes")]
public List<notes> ListNotes { get; set; }
}
public class notes
{
[XmlIgnore]
public string Note { get; set; }
}
一2班,当我序列化在这本然后我得到的XML甲酸盐
<product Id="1">
<name>2 1/2 X 6 PVC NIPPLE TOE SCH 80</name>
<notes>
<notes>
<note>!--note 1---</note>
<note>!--note 2--</note>
</notes>
</notes>
</product>
我不想额外<notes>
。任何连击解决方案来解决这个问题? 感谢
解决方案
public class product
{
[XmlElement("name")]
public string Name { get; set; }
[XmlArray("notes")]
public List<notes> ListNotes { get; set; }
}
public class notes
{
[XmlText]
public string Note { get; set; }
}
product ObjProduct = new product
{
Name ="Pankaj",
notes=new List<note>()
}
foreach (var note in item.ListNote)
{
ObjProduct.notes.Add(new Highmark.BLL.Common.note { Note = EncodeTo64(note.Note) });
}
现在使用这个ObjProduct进行序列化。
答
尝试这样的:
[XmlRoot("product")]
public class Product
{
[XmlAttribute]
public int Id { get; set; }
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("note")]
public List<Note> ListNotes { get; set; }
}
public class Note
{
[XmlText]
public string Text { get; set; }
}
class Program
{
public static void Main()
{
var p = new Product
{
Id = 1,
Name = "2 1/2 X 6 PVC NIPPLE TOE SCH 80",
ListNotes = new List<Note>
{
new Note { Text = "!--note 1---" },
new Note { Text = "!--note 2---" },
}
};
var serializer = new XmlSerializer(p.GetType());
serializer.Serialize(Console.Out, p);
}
}
如果你想从根节点删除的命名空间:
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
serializer.Serialize(Console.Out, p, ns);
答
这并不直接回答你的问题,但如果你不能解决这个问题,你可以创建一个Schema.xsd文件,并使用.NET的XSD工具为你生成正确的序列化类。
我已经取得了相当不错的成功。
使用模式的明显好处是在序列化之前验证XML。
答
尝试这样的:
class Program
{
static void Main(string[] args)
{
var product = new Product() { Name = "PVC SCHOOL" };
product.Notes = new List<note>();
product.Notes.Add(new note() { Note = "A" });
product.Notes.Add(new note() { Note = "B" });
var serialer = new XmlSerializer(typeof(Product));
using (var stream = new StreamWriter("test.txt"))
{
serialer.Serialize(stream, product);
}
}
}
public class Product
{
[XmlElement("name")]
public string Name { get; set; }
[XmlArray("notes")]
public List<note> Notes { get; set; }
}
public class note
{
[XmlIgnore]
public string Note { get; set; }
}
+0
谢谢@@ Soe ..但是这是忽略笔记数据并显示像这样的结果
感谢绅士,我得到解决方案。 – Pankaj 2010-06-03 07:29:28