/// <summary>
/// 追加節點
/// </summary>
/// <param name="filePath">XML文檔絕對路徑</param>
/// <param name="xPath">范例: @"Skill/First/SkillItem"</param>
/// <param name="xmlNode">XmlNode節點</param>
/// <returns></returns>
public static bool AppendChild(string filePath, string xPath, XmlNode xmlNode)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNode xn = doc.SelectSingleNode(xPath);
XmlNode n = doc.ImportNode(xmlNode, true);
xn.AppendChild(n);
doc.Save(filePath);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 從XML文檔中讀取節點追加到另一個XML文檔中
/// </summary>
/// <param name="filePath">需要讀取的XML文檔絕對路徑</param>
/// <param name="xPath">范例: @"Skill/First/SkillItem"</param>
/// <param name="toFilePath">被追加節點的XML文檔絕對路徑</param>
/// <param name="toXPath">范例: @"Skill/First/SkillItem"</param>
/// <returns></returns>
public static bool AppendChild(string filePath, string xPath, string toFilePath, string toXPath)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(toFilePath);
XmlNode xn = doc.SelectSingleNode(toXPath);
XmlNodeList xnList = ReadNodes(filePath, xPath);
if (xnList != null)
{
foreach (XmlElement xe in xnList)
{
XmlNode n = doc.ImportNode(xe, true);
xn.AppendChild(n);
}
doc.Save(toFilePath);
}
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 修改節點的InnerText的值
/// </summary>
/// <param name="filePath">XML文件絕對路徑</param>
/// <param name="xPath">范例: @"Skill/First/SkillItem"</param>
/// <param name="value">節點的值</param>
/// <returns></returns>
public static bool UpdateNodeInnerText(string filePath, string xPath, string value)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNode xn = doc.SelectSingleNode(xPath);
XmlElement xe = (XmlElement)xn;
xe.InnerText = value;
doc.Save(filePath);
}
catch
{
return false;
}
return true;
}
/// <summary>
/// 讀取XML文檔
/// </summary>
/// <param name="filePath">XML文件絕對路徑</param>
/// <returns></returns>
public static XmlDocument LoadXmlDoc(string filePath)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
return doc;
}
catch
{
return null;
}
}
/// <summary>
/// 讀取XML的所有子節點
/// </summary>
/// <param name="filePath">XML文件絕對路徑</param>
/// <param name="xPath">范例: @"Skill/First/SkillItem"</param>
/// <returns></returns>
public static XmlNodeList ReadNodes(string filePath, string xPath)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNode xn = doc.SelectSingleNode(xPath);
XmlNodeList xnList = xn.ChildNodes; //得到該節點的子節點
return xnList;
}
catch
{
return null;
}
}
閱讀原文:原文鏈接
該文章在 2025/1/11 18:19:47 編輯過