首先,我很抱歉,我知道我的問題將是非常基本的東西,但請我真的很感謝一些幫助,我承受了很大的壓力,所以做出了聰明的評論和存在諷刺並不會幫助從xml文件構建類
我有這段代碼: 至少我在嘗試。 我有這個xml文件,我需要將它的所有屬性保存在一個類中,這樣我只需要時就可以複製它。
我不知道該怎麼辦。
public static void firstFileXml(string sXml1)
{
var root = XElement.Load(@"sXml1");
var controlElementsFirst = root.Descendants("books");
}
的XML文件具有類似屬性:標籤,文本,LABEL_W等 我需要一個函數或somethign,讓我像進入: 探索(xmlLocation),並做休息。 因爲我需要做幾個XML文件
我需要建立一個類,讓我讀它。 假設我有XML的文件:
WAS
<books>
<book label='' page='' intro =''/>
<book label='' page='' intro =''/>
<book label='' page='' intro =''/>
</books>
IS
<SHEET>
<books>
<book label='1' page='1' intro='1'/>
<book label='2' page='2' intro='2'/>
<book label='3' page='3' intro='3'/>
</books>
</SHEET>
等。 我需要先讀這個XML文件,然後存儲在一個類的書屬性,這樣我就可以使用它的數百本書籍後
代碼:
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
static class Program
{
static void Main()
{
// get the xml as a string; note that we could also use
// Deserialize(Stream) to process a FileStream, but this
// works fine
string xml = File.ReadAllText(@"C:\Users\books.xml");
var ser = new XmlSerializer(typeof(BookRoot));
var root = (BookRoot)ser.Deserialize(new StringReader(xml));
foreach (var book in root.Books)
{
Console.WriteLine("label: " + book.Label);
Console.WriteLine("page: " + book.Page);
Console.WriteLine("intro: " + book.Intro);
Console.ReadLine();
}
}
}
[XmlRoot("SHEET")]
public class BookRoot
{
private readonly List<Book> books = new List<Book>();
[XmlArray("books"), XmlArrayItem("book")]
public List<Book> Books { get { return books; } }
}
public class Book
{
[XmlAttribute("label")]
public string Label { get; set; }
[XmlAttribute("page")]
public string Page { get; set; }
[XmlAttribute("intro")]
public string Intro { get; set; }
}
您正在尋找的XML序列化 – 2014-09-02 07:55:38
和反序列化 – Sayse 2014-09-02 07:56:46
不是真的,因爲他們有節點而我主要使用屬性。請真正感謝一些示例算法或小代碼,只是有一個想法 – 2014-09-02 07:58:22