C#讀寫xml

讀:

XmlDocument xmlDoc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
settings.IgnoreWhitespace = true;
XmlReader reader = null;
reader = XmlReader.Create(fileName, settings);
xmlDoc.Load(reader);
//獲取名爲Root的節點
XmlNode root = xmlDoc.SelectSingleNode("Root");
//節點的屬性,clazz屬性值
XmlAttribute xmlAttr = root.Attributes["clazz"];
String type = xmlAttr == null ? null : xmlAttr.Value;
//遍歷這個節點的子節點
foreach(XmlNode subNode in root){
    //節點值
    subNode.Value;
}

寫:

XmlDeclaration Declaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
xmlDoc.InsertBefore(Declaration, xmlDoc.DocumentElement);
//創建Root節點
XmlNode rootNode = xmlDoc.CreateElement("Root");
xmlDoc.AppendChild(rootNode);
//Root的子節點branch
XmlNode branch=xmlDoc.CreateElement("branch");
rootNode.AppendChild(branch);
//給branch添加屬性type="branch"
XmlAttribute attr=xmlDoc.CreateAttribute("type");
attr.Value="branch";
branch.Attributes.Append(attr);
//保存到文件
xmlDoc.save(fileName);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章