2011-12-12 80 views
0

如何用此字符串編寫.xml文件?用字符串編寫XML

字符串:

string string1 = textbox1.text; 
string string2 = textbox2.text; 
string string3 = textbox3.text; 
string string4 = textbox4.text; 

xml文件的結果:

<?xml version="1.0" encoding="utf-8" ?> 
     <books> 
      <book Title="Pure JavaScript" Price=string1/> 
      <book Title="Effective C++" Price=string2/> 
      <book Title="Assembly Language: Step-By-Step" Price=string3/> 
      <book Title="Oracle PL/SQL Best Practices" Price=string4/> 
     </books> 
+0

您的代碼示例中有8個不同的字符串,並且由於默認命名,我們不知道每個字符的含義。很難看出這些應該如何與您的XML相匹配。 – Oded

+0

XML也是無效的,因爲'Price'屬性沒有引用值。 – Oded

回答

3

您可以使用Linq to XML來做到這一點。假設你有一個類Book

class Book 
{ 
    public string Title { get; set; } 
    public decimal Price { get; set; } 
} 

現在你要投入到XML文檔的書籍列表:

List<Book> books = new List<Book>(); 
books.Add(new Book() { Title = "Pure JavaScript", Price = 59.0M}); 

XDocument xdoc = new XDocument(new XElement("books", books.Select(x=> new XElement("book", 
           new XAttribute("Title", x.Title), 
           new XAttribute("Price", x.Price))))); 

現在,你可以保存這個XDocument

xdoc.Save("text.xml"); 

這產生:

<books> 
    <book Title="Pure JavaScript" Price="59.0" /> 
</books> 
+0

用於打字比我快(相同的概念和代碼)+1。 – 2011-12-12 19:24:47

+0

非常感謝!完美 – jolly

+0

不好意思,但是爲了創建一個? – jolly

0

退房System.Xml命名空間。特別的XmlDocument和XmlNode的

而且XML文本(我知道VB有他們,不知道C#)

+1

C#沒有XML文字。 – Oded

+0

@Oded:謝謝。 –

0

看看這些關鍵字:

  1. XmlWriter
  2. XDocument
  3. XmlDocument
  4. 序列化

我覺得,在你的情況下XmlWriter是最好的選擇。

+0

-1用於推薦'XmlTextWriter',它不應該直接使用。 –

+0

@JohnSaunders,好吧,'XmlWriter'。我在哪裏推薦直接使用它? –

+0

你提到它。爲什麼要在要使用的東西列表中提到它? –