C# XML讀寫

      在〈C# XML讀寫〉中尚無留言

功能

在c#裏, 若使用webBrowser元件, 常需要自行撰寫 html, 然後再放入webBrowser裏. 如下

StringBuilder sb = new StringBuilder();
sb.Append("<html><head><title>test<title></head><body>......</body></html>");
web.NavigateToString(sb.ToString());

sb.Append()那一串, 就是在撰寫html的語法. 那還得了, 這麼長的一串文字, 不是少了 “>”, 就是多了 “/”.

那有什麼方法可以幫我們寫html的語法呢? XmlDocumnet就是我們的救星

XmlDocment

1. 先產生XmlDocment物件 doc
2. 任何標籤皆由doc產生.
3. 父標籤使用 AppendChild()加入子標籤
4. 標籤內容使用InnerText指定

XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.AppendChild(dec);
var html = doc.CreateElement("html");
doc.AppendChild(html);
var head = doc.CreateElement("head");
html.AppendChild(head);
var title = doc.CreateElement("title");
title.InnerText = "MahalJsp";
head.AppendChild(title);

XmlDocment to String

將XmlDocment轉換成String的流程如下圖

xml

1. 先產生StringWriter物件
2. StringWriter塞入XmlWriter物件.
3. 把XmlDocument寫到XmlWriter中
4. 由StringWriter轉成StringBuilder再轉成String

using (StringWriter stringWriter = new StringWriter())
using(XmlWriter xmlWriter = XmlWriter.Create(stringWriter))
{
    doc.WriteTo(xmlWriter);
    xmlWriter.Flush();
    Console.WriteLine(stringWriter.GetStringBuilder().ToString());
}

完整程式碼

using (StringWriter stringWriter = new StringWriter())
using(XmlWriter xmlWriter = XmlWriter.Create(stringWriter))
{
    XmlDocument doc = new XmlDocument();
    XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
    doc.AppendChild(dec);
    var html = doc.CreateElement("html");
    doc.AppendChild(html);
    var head = doc.CreateElement("head");
    html.AppendChild(head);
    var title = doc.CreateElement("title");
    title.InnerText = "MahalJsp";
    head.AppendChild(title);
    var body = doc.CreateElement("body");
    html.AppendChild(body);

    doc.WriteTo(xmlWriter);
    xmlWriter.Flush();
    Console.WriteLine(stringWriter.GetStringBuilder().ToString());
    //doc.Save("tmp.html");
}

請注意, doc.Save()可以直接儲存成檔案

tmp.html結果如下

<?xml version="1.0" encoding="utf-8"?>
<html>
    <head>
       <title>MahalJsp</title>
    </head>
    <body />
</html>

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *