Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Attribute to XML node C#

I am trying to add an attribute to XML node

Actual Value

<Hardships>
<Hardship IsPrimary="true" EstimatedHardshipDuration="MEDIUM" HardshipReason="UNEMP" IsSeekingEmployment="Y" IsResolveableIn3MonthsVerbal="N" />
</Hardships>

Expected after node Change

<Hardships>
<Hardship IsPrimary="true" EstimatedHardshipDuration="MEDIUM" HardshipReason="UNEMP" IsSeekingEmployment="Y" IsResolveableIn3MonthsVerbal="N" HardshipEndDate="11/21/2017 12:00:00 AM/>
</Hardships>

I wrote code like this

var requestDocument = new XmlDocument();
requestDocument.LoadXml(requestString);
var todayDate = DateTime.Today.Date;
var hardShipEndDate = todayDate.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK");
var HardshipDudeNode = requestDocument.SelectSingleNode(HardshipWorkoutOptionsRequestNodeXml);
//adding an attribute to XML node
HardshipDudeNode.Attributes.Append(requestDocument.CreateAttribute("HardshipEndDate", hardShipEndDate));

I am getting an output like this

<Hardships>
 <Hardship IsPrimary="true" EstimatedHardshipDuration="MEDIUM" HardshipReason="UNEMP" IsSeekingEmployment="Y" IsResolveableIn3MonthsVerbal="N" IsResolveableIn6MonthsDocumented="Y" p7:HardshipEndDate=""
xmlns:p7="2017-11-21T00:00:00.0000000-05:00" />
</Hardships>     

why i am getting the attribute like his "p7:HardshipEndDate="" xmlns:p7="2017-11-21T00:00:00.0000000-05:00" ? can someone help me out.

like image 211
rackhwan Avatar asked Sep 12 '26 01:09

rackhwan


1 Answers

Because first argument here is element name and second is namespace:

requestDocument.CreateAttribute("HardshipEndDate", hardShipEndDate)

And you don't set value anywhere. Instead do it like this:

var hardShipEndDate = todayDate.ToString("G");
var endDateAttr = requestDocument.CreateAttribute("HardshipEndDate");
endDateAttr.Value = hardShipEndDate;
HardshipDudeNode.Attributes.Append(endDateAttr);

Note that such datetime format is unusual for xml. If you are not required to produce dates in that specific format, better use

// or XmlDateTimeSerializationMode.Local
var hardShipEndDate = XmlConvert.ToString(todayDate, XmlDateTimeSerializationMode.Utc);
like image 177
Evk Avatar answered Sep 14 '26 15:09

Evk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!