[C#]建立XML文件
實作:
需求:要組成一個如下圖,包含有「version」,「encoding」,「DOCTPYE」等資訊的XML文件。
1.建立一個 XML Build 來組成 XML文件
public class XMLBuild { private XmlDocument _xmlDoc { get; set; } public XMLBuild() { _xmlDoc = new XmlDocument(); } /// <summary> /// 將XML 文件 儲存至 指定路徑 /// </summary> /// <param name="path"></param> public void Save(string path) { if(string.IsNullOrWhiteSpace(path)) { return; } _xmlDoc.Save(path); } /// <summary> /// 將XML 文件 儲存至 指定串流 /// </summary> /// <param name="stream"></param> /// <returns></returns> public MemoryStream Save(MemoryStream stream) { _xmlDoc.Save(stream); return stream; } /// <summary> /// 建立具有指定值的 XmlDeclaration 節點 /// </summary> /// <param name="version"></param> /// <param name="encoding"></param> /// <param name="standalone"></param> public void CreateXmlDeclaration(string version, string encoding, string standalone) { XmlDeclaration xmlDeclaration = _xmlDoc.CreateXmlDeclaration(version, encoding, standalone); _xmlDoc.AppendChild(xmlDeclaration); } /// <summary> /// 建立 DocumentType /// </summary> /// <param name="name"></param> /// <param name="publicId"></param> /// <param name="systemId"></param> /// <param name="internalSubset"></param> public void CreateDocumentType(string name, string publicId, string systemId, string internalSubset) { var doctype = _xmlDoc.CreateDocumentType(name, publicId, systemId, internalSubset); _xmlDoc.AppendChild(doctype); } /// <summary> /// 將指定的節點加入在XML文件底下 /// </summary> /// <param name="element"></param> public void AddRootElement(XmlElement element) { _xmlDoc.AppendChild(element); } /// <summary> /// 建立具有指定名稱的項目 /// </summary> /// <param name="name"></param> /// <param name="innerText"></param> /// <returns></returns> public XmlElement CreateElement(string name, string innerText) { var element = _xmlDoc.CreateElement(name); if (innerText != null) { element.InnerText = innerText; } return element; } }
留言
張貼留言