Reputation: 111
hai friends i need to update an xml file with node attributes my xml structure is
<BankName BankName="jinesh" TemplateModel="sam">
<ChqBasics>
<ChqL>30</ChqL>
<ChqW>50</ChqW>
<ChqImgPath>hai</ChqImgPath>
</ChqBasics>
<XandYPosition>
<column Name="ChqDate" X="10" Y="10" />
<column Name="CPayAgainst" X="10" Y="10" />
<column Name="ChqAmtDgt" X="10" Y="10" />
<column Name="ChqAmtWrds" X="10" Y="10" />
</XandYPosition>
i need to update the elements in the XandYPosition node so i created a function for this but i am not able to complete this .please help me to achieve this
public static void updatenode(string bankname, string templatemodel,string field,string x,string y)
{
XDocument doc = XDocument.Load("newtest.xml");
var updatenode = doc
.Descendants("BankName")
.Where(item => item.Attribute("BankName").Value == bankname && item.Attribute("TemplateModel").Value == templatemodel)
.Select(XandYPosition => XandYPosition.Descendants("XandYPosition").Descendants());
}
function call will be like this
BasicClass.updatenode(comboBox1.Text, comboBox2.Text, "ChqDate", "1000", "2000");
please help to make the code complete
Upadte: How can i update the BankName="Jinesh" with "XYZ"
Upvotes: 1
Views: 1002
Reputation: 6368
Try this code, if you get errors please feel free to ask:
public static void updatenode(string bankname, string templatemodel,string field,string X,string Y)
{
XDocument xDoc = XDocument.Load("../../newTest.xml");
IEnumerable<XElement> updatenode = xDoc.Descendants("BankName")
.Where(x => x.Attribute("BankName").Value == bankname && x.Attribute("TemplateModel").Value == templatemodel)
.Select(x => x.Element("XandYPosition").Elements("column")).FirstOrDefault();
updatenode.Where(x => x.Attribute("Name").Value == field).FirstOrDefault().Attribute("X").Value = X;
updatenode.Where(x => x.Attribute("Name").Value == field).FirstOrDefault().Attribute("Y").Value = Y;
xDoc.Save("../../newTest.xml");
}
Note:
Replace ../../newTest.xml
with the path of your xml file.
Update:
XDocument xDoc = XDocument.Load("../../newTest.xml");
XElement updatenode = xDoc.Descendants("BankName")
.Where(x => x.Attribute("BankName").Value == "jinesh" && x.Attribute("TemplateModel").Value == "sam")
.Select(x => x.Element("ChqBasics").Element("ChqL")).FirstOrDefault();
updatenode.Value = "130";
xDoc.Save("../../newTest.xml");
For more references please watch these videos on this youtube channel :
https://www.youtube.com/playlist?list=PL6n9fhu94yhX-U0Ruy_4eIG8umikVmBrk
Upvotes: 2