維祥's profile焗烤蝦米工坊PhotosBlogLists Tools Help

Blog


    October 07

    使用Linq to XML 來讀取XML檔案的範例程式

    有一長段時間沒有發相關的技術文章了 (迷之聲: 你在混嘛~)

    這次在協助處理讀取XML變成亂碼的問題,後來發現是因為使用了FileInfo.OpenText()的方式來讀取檔案

    但好死不死那個檔案竟然是BIG5編碼,偏偏FileInfo.OpenText () 是使用 UTF-8的編碼方式來讀取檔案,請參考下方連結

    FileInfo.OpenText 方法

    原本是改成使用StreamReader 的方法,指定讀取的編碼方式為BIG5

       1:  using (StreamReader sr = new StreamReader(fi.FullName, Encoding.GetEncoding("big5")))
       2:  {
       3:      return sr.ReadToEnd();
       4:  }

     

    但是,這樣寫又把程式給寫死了,如果今天遇到編碼是UTF8,那不就掛了嗎?

    原本的想法是,先偵測檔案編碼格式,在使用對應的編碼去開取檔案,不過,經理提供了一個更好做法

    使用LINQ to XML來讀取XML檔,可參考下列連結

    HOW TO:讀取和寫入編碼的文件

    只要以下這一行,即可輕鬆解決檔案編碼問題

       1:  XDocument xdoc = XDocument.Load(_filePath);
     

    是的! 你沒看錯,只要一行,他就會幫你把XML檔案讀取進來,不管是UTF8 或是 BIG5,都可以自動使用相對應的編碼來讀取

    不過要特別注意,如果你在XML中宣告編碼與檔案儲存的編碼格式不同,他還是沒辦法讀取喔!!

    舉例來說:

    XML文件中宣告

    <?xml version="1.0" encoding="UTF-8"?>

    但是XML卻是使用BIG5的編碼方式儲存

    這樣讀取還是出現錯誤。

    本人有寫一隻小程式,可以下載下來參考看看

    (是使用VS2008開發的喔)

    以下是測試程式的相關截圖

    Default_form UTF8

    UTF8UTF8BIG5

    Comments

    Please wait...
    Sorry, the comment you entered is too long. Please shorten it.
    You didn't enter anything. Please try again.
    Sorry, we can't add your comment right now. Please try again later.
    To add a comment, you need permission from your parent. Ask for permission
    Your parent has turned off comments.
    Sorry, we can't delete your comment right now. Please try again later.
    You've exceeded the maximum number of comments that can be left in one day. Please try again in 24 hours.
    Your account has had the ability to leave comments disabled because our systems indicate that you may be spamming other users. If you believe that your account has been disabled in error please contact Windows Live support.
    Complete the security check below to finish leaving your comment.
    The characters you type in the security check must match the characters in the picture or audio.

    To add a comment, sign in with your Windows Live ID (if you use Hotmail, Messenger, or Xbox LIVE, you have a Windows Live ID). Sign in


    Don't have a Windows Live ID? Sign up

    Trackbacks

    The trackback URL for this entry is:
    http://sfcer0414.spaces.live.com/blog/cns!9B25575939B45309!1455.trak
    Weblogs that reference this entry
    • None