Charu
Charu

Reputation: 2749

Easier way to add elements in XML using LINQ

Currently i am using xpath with linq to xml to add elements after a particular element in a xml document. My concern is if this hierarchy is too deep , i have to mention the complete hierachy always? Can't i directly somehow give the name of the Element after which i want to add my new element.

In this code i am talking about this hierarchy: SESSIONANALYSER/AP/MODES/NI/STATEINFORMATION/INIT/INPUT[@VALUE='SLN7DEACTIVATION']/METHOD

String strFile = File.ReadAllText(Server.MapPath("~/SessionAnalyserAccessories.xml"));
            XDocument xdoc1 = XDocument.Parse(strFile);
            xdoc1.XPathSelectElement("SESSIONANALYSER/AP/MODES/NI/STATEINFORMATION/INIT/INPUT[@VALUE='SLN7DEACTIVATION']/METHOD").AddAfterSelf(new XElement("METHOD", "", new XAttribute("NAME", "CHECKSUBSCRIBERBALANCE1"), new XAttribute("PARAMETERS", "SLN7"), new XAttribute("POSSIBLEACTIONS1", "FALLOUTON_FAILUREREGION_SETPSOFAILED_FALSE1"), new XAttribute("MAINTAINSESSION", "NO"), new XAttribute("RESPONSE", "-4"), new XAttribute("NEXTLEVEL", "")));

Upvotes: 0

Views: 131

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167461

Well with XPath you can use descendant::INPUT[@VALUE='SLN7DEACTIVATION']/METHOD or //INPUT[@VALUE='SLN7DEACTIVATION']/METHOD to find elements at any level thus if you are sure there is only one such element you can shorten your path that way. However if all the ancestors matter to identify the element then use the long path.

On a side note, instead of

String strFile = File.ReadAllText(Server.MapPath("~/SessionAnalyserAccessories.xml"));
XDocument xdoc1 = XDocument.Parse(strFile);

simply do

XDocument xdoc1 = XDocument.Load(Server.MapPath("~/SessionAnalyserAccessories.xml"));

that allows the XML parser to find the right encoding in the XML declaration of the document and should be more efficient by not first reading in a lengthy string with all XML.

Upvotes: 2

Related Questions