Reputation: 43
I have XML which is in project folder. I am loading the contents using this
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 has following nodes
<ClaimKeyInfo>
<CompanyID>XXXX</CompanyID>
<ClaimNum>XX-XXXXX-XX<ClaimNum>
</ClaimKeyInfo>
<ClaimInfo>
<ClaimNum>XX-XXXXX-XX</ClaimNum>
<ClaimSensitivityInd>N</ClaimSensitivityInd>
<ClaimStatus>Open</ClaimStatus>
<ClaimInfo>
I am doing this to get ClaimNum elements
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);
}
I do get both the elements in elemList but I am not able to change the values inside it.
Any help would be appreciated.
Upvotes: 0
Views: 74
Reputation: 101701
You can use LINQ to XML
for that.
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");
Here, the numbers
are contains XElements
which is your ClaimNums
.You can change the Value
property and save the XML
file.If you want to get specific numbers you can use Where
extension method.If you want more details see these documentations:
Upvotes: 1