1. 新增XML文件
</div>上述代码实现效果:
那在Person节点继续增加节点,实现也很简单
</div>上述代码实现效果:
2.读取节点的值,个人感觉xpath方式比linq to xml更为明了方便
上述代码实现效果:3.格式化显示XML
上述代码实现效果:4.XMLToolV2源代码
public XMLToolV2(string xmlPath)
{
_xmlPath = xmlPath;
LoadXmlDoc();
}
public XmlNode Select(string xPath)
{
if (string.IsNullOrEmpty(xPath))
throw new ArgumentNullException("xPath");
return _xmlDoc.SelectSingleNode(xPath);
}
public XmlNodeList SelectNodeList(string xPath)
{
if (string.IsNullOrEmpty(xPath))
throw new ArgumentNullException("xPath");
return _xmlDoc.SelectNodes(xPath);
}
public void Create(string rootName, string encode)
{
CreateXmlDoc(rootName, encode);
}
private void CreateXmlDoc(string rootName, string encode)
{
if (!File.Exists(_xmlPath))
{
if (string.IsNullOrEmpty(rootName))
throw new ArgumentNullException(rootName);
_xmlDoc = new XmlDocument();
XmlDeclaration _xmldecl = _xmlDoc.CreateXmlDeclaration("1.0", encode, null);
_xmlDoc.AppendChild(_xmldecl);
_xmlRoot = _xmlDoc.CreateElement("", rootName, "");
_xmlDoc.AppendChild(_xmlRoot);
}
}
public void LoadXmlDoc()
{
if (File.Exists(_xmlPath))
{
_xmlDoc = new XmlDocument();
_xmlDoc.Load(_xmlPath);
_xmlRoot = _xmlDoc.DocumentElement;