創建一個xml文件的步驟:
新建一個XElement對象,為這個對象賦值。我這里的最外層節點名稱叫:Smart2000,它里面包含兩個節點,“SuperPin”和“Modules”,在這里,“SuperPin”節點的值是固定的,在聲明xml文件時就直接初始化,兒“Modules”節點的值沒有固定,在這里就直接寫入,聲明存在這個節點,並不指定“Modules”節點里的格式。
不指定Modules的格式:
public static XElement GenerateXmlFile(string appId)
XElement myXDoc = new XElement(
new XElement("Smart2000",
new XElement("SuperPin", superPin),
new XElement("Modules")
);
new XElement("Smart2000",
new XElement("SuperPin", superPin),
new XElement("Modules")
);
}
指定Modules的格式:
public static XElement GenerateXmlFile(string appId)
XElement myXDoc = new XElement(
new XElement("Smart2000",
new XElement("SuperPin", superPin),
new XElement("Modules",
new XElement("Modules",
new XAttribute("ID", "0"),
new XAttribute("enable", "true"),
new XAttribute("name", "Module" + 0),
new XAttribute("Data", "")
)
new XElement("Smart2000",
new XElement("SuperPin", superPin),
new XElement("Modules",
new XElement("Modules",
new XAttribute("ID", "0"),
new XAttribute("enable", "true"),
new XAttribute("name", "Module" + 0),
new XAttribute("Data", "")
)
)
);
);
}
當我想在別的地方調用這個方法,並且還要為這個xml文件下的“Modules”節點新添加節點的時候,如果初始化的時候沒有指定格式,那這里就可以直接寫添加節點的方法,如果初始化了,那么可以判斷一下初始化節點,然后RemoveAll()刪除掉該節點,然后添加符合條件的數據
/// <summary>
/// 修改節點的值
/// </summary>
/// <param name="myXDoc">原xml文件</param>
/// <param name="num">模塊序號</param>
/// <param name="name">模塊名稱</param>
/// <param name="data">模塊數據[此處暫不做要求]</param>
/// <returns>添加新節點后的xml文件</returns>
public static XElement GenerateModuleUpdateAdd(XElement myXDoc, int num, string name, string data)
{
XElement xele = myXDoc.Element("Modules"); //在xml文件里取出該節點
XElement x = xele.Element("Modules"); //在該節點下取到第一行初始化的數據
//刪除第一行數據 ps:由於水平有限,沒有找到怎么替換第一行數據的方法,就干脆刪掉,重新添加第一行符合條件的數據
if (Convert.ToString(x.Attribute("name").Value) == "Module0")
{
xele.RemoveAll();//刪除該節點的全部內容
}
/// 修改節點的值
/// </summary>
/// <param name="myXDoc">原xml文件</param>
/// <param name="num">模塊序號</param>
/// <param name="name">模塊名稱</param>
/// <param name="data">模塊數據[此處暫不做要求]</param>
/// <returns>添加新節點后的xml文件</returns>
public static XElement GenerateModuleUpdateAdd(XElement myXDoc, int num, string name, string data)
{
XElement xele = myXDoc.Element("Modules"); //在xml文件里取出該節點
XElement x = xele.Element("Modules"); //在該節點下取到第一行初始化的數據
//刪除第一行數據 ps:由於水平有限,沒有找到怎么替換第一行數據的方法,就干脆刪掉,重新添加第一行符合條件的數據
if (Convert.ToString(x.Attribute("name").Value) == "Module0")
{
xele.RemoveAll();//刪除該節點的全部內容
}
//添加符合條件的數據
xele.Add(new XElement("Module",
new XAttribute("id", num),
new XAttribute("enable", "true"),
new XAttribute("name", name),
new XAttribute("Data", data)));
return myXDoc;
}
xele.Add(new XElement("Module",
new XAttribute("id", num),
new XAttribute("enable", "true"),
new XAttribute("name", name),
new XAttribute("Data", data)));
return myXDoc;
}
如果有多條數據要添加到這個節點下面,我認為把要添加的數據存入數組,然后循環數組調用該方法即可。
這些是我這兩天操作一個xml文件所理解的東西。學習學習再學習!:)