2014-02-21 166 views
0

我有位於項目文件夾中的XML。我加載使用此更改XML元素的值

XmlDocument doc = new XmlDocument(); 
    string testFilesLocation = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); 
    string dataSource; 
    string xmlFileName = "Claim.txt"; 

    if (System.IO.Directory.Exists(testFilesLocation + @"\Resources")) 
    { 
     dataSource = testFilesLocation + @"\Resources\" + xmlFileName; 
    } 
    else 
    { 
     dataSource = testFilesLocation + @"\" + xmlFileName; 
    } 
    doc.Load(dataSource); 

XML的內容有以下節點

<ClaimKeyInfo> 
    <CompanyID>XXXX</CompanyID> 
    <ClaimNum>XX-XXXXX-XX<ClaimNum> 
</ClaimKeyInfo> 

<ClaimInfo> 
    <ClaimNum>XX-XXXXX-XX</ClaimNum> 
    <ClaimSensitivityInd>N</ClaimSensitivityInd> 
    <ClaimStatus>Open</ClaimStatus> 
<ClaimInfo> 

我這樣做是爲了讓ClaimNum元素

XmlElement root = doc.DocumentElement; 
    XmlNodeList elemList = root.GetElementsByTagName("ClaimNum"); 
    for (int i = 0; i< elemList.Count; i++) 
    { 
     elemList[i].InnerXml = "YY-YYYYY-YY"; 
     doc.Save(dataSource); 
    } 

我得到既elemList但我的元素我無法改變它裏面的值。

任何幫助,將不勝感激。

+0

向我們展示您嘗試更改節點值的代碼。 – Tony

回答

1

您可以使用LINQ to XML

var xDoc = XDocument.Load("filePath"); 
var numbers = xDoc.Descendants("ClaimNum"); 

foreach(var number in numbers) 
{ 
    // do your work with numbers 
    number.Value = "123456"; 
} 

xDoc.Save("filePath"); 

這裏,numbers是包含XElements這是您的ClaimNums。你可以改變Value財產和保存XML文件。如果你想要得到具體的數字你可以使用Where擴展你method.If想了解更多詳細信息看到這些單證: