最近在寫C# xml解析相關代碼,遇到一個花了幾個小時才解決得問題,記錄下:
其實比驕傲簡單,從一個xml裏面讀取數據,然後在從其中抽取自己想要得數據,然後寫入另外一個xml中;
string readXml = File.ReadAllText(xmlPath);
foreach (var item_case in item_result_Info.Elements("AutoTest_CASE"))
{
testCase_Writer = new StreamWriter(new FileStream((testCase_NameFile), FileMode.Create));
testCase_Writer.WriteLine("<AutoTest_CASE>");
testCase_Writer.WriteLine("\t" + item_case.Element("/TestCase_Name"));
testCase_Writer.WriteLine("\t" + item_case.Element("TestCase_Index"));
}
重點在紅色部分,報錯原因提示xml異常,不能以"/"開頭, 實際源xml文件中沒有 “/TestCase_Name” ,是我手誤多寫了一個 "/"導致異常得。
解決方法:testCase_Writer.WriteLine("\t" + item_case.Element("TestCase_Name")); 即item_case.Element要確保 傳值 是其中節點
同樣寫入數據可以 按照下面方式寫入,不過沒有上面方便簡單:
testCase_Writer.WriteLine("\t<TestCase_Name>" + testCase_Name + "</TestCase_Name>");