2020年4月9日 星期四

[C#]XML 相關操作

最近因為開發某個功能需要跟別的系統介接
發現對方的存取都是透過XML string
最方便的方法就是透過string直接做處理
但是一下轉string,一下轉XMLElement
如果資料的數量多,難免會影響效能

後來想了,如果一開始就透過XDocument做處理
是不是可以省去轉string或XML Element的步驟
找了網路上的方法,整理會用到的功能
有新增欄位、刪除欄位、變更tag名稱


static void Main(string[] args) {
 XElement bookElement = new XElement("book");
 XDocument doc = new XDocument(bookElement);

 AddElement(ref doc, "author", "Gambardella, Matthew");
 AddElement(ref doc, "title", "XML Developer's Guide");
 AddElement(ref doc, "genre", "Computer");
 AddElement(ref doc, "price", 44.95);
 AddElement(ref doc, "publish_date", new DateTime(2000, 1, 1));
 AddElement(ref doc, "description", "An in-depth look at creating applications with XML.");
 Console.WriteLine(doc.ToString());

 ReplaceTagName(ref doc, "description", "memo");
 Console.WriteLine(doc.ToString());

 RemoveElement(ref doc, "genre");
 Console.WriteLine(doc.ToString());
}


// 更換xml的tag name
public static void ReplaceTagName(ref XDocument doc, string origTagName, string newTagName) {
 foreach (var element in doc.Descendants()) {
  if (element.Name.LocalName.Equals(origTagName)) {
   element.Name = newTagName;
  }
 }
}

// 新增欄位
public static void AddElement(ref XDocument doc, string elementName, object elementValue) {
 try {
  doc.Root.Add(new XElement(elementName, elementValue));
 } catch (Exception e) {
  Console.WriteLine("AddElement error:" + doc.ToString() + Environment.NewLine + e.StackTrace);
 }
}

// 移除欄位
public static void RemoveElement(ref XDocument doc, string elementName) {
 try {
  doc.Descendants().SingleOrDefault(p => p.Name == elementName).Remove();
 } catch (Exception e) {
  Console.WriteLine("RemoveElement error:" + doc.ToString() + Environment.NewLine + e.StackTrace);
 }
}



如果想把XML直接轉成class
Visual Studio有支援可以把XML或JSON轉成 class
路徑: Edit -> Paste Special -> Paste XML As Classes 
轉完之後,再查看一下欄位的格式是否是想要的
有了class可以少去一個欄位一個欄位對應轉換成XML

產生的XML string驗證是否正確
可以透過以下兩個網頁來檢驗
1. https://www.freeformatter.com/xml-formatter.html#ad-output
2. https://codebeautify.org/xmlvalidator

沒有留言:

張貼留言