3

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.

rackhwan
  • 265
  • 5
  • 14
  • The is no reason your formatting should not work. Try declaring the string as a string instead of var : string hardShipEndDate = todayDate.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK"); – jdweng Nov 22 '17 at 02:45

2 Answers2

3

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);
Evk
  • 98,527
  • 8
  • 141
  • 191
0

Basically the format you set, is not what you want it to be. According to this link all you need to change is:

var hardShipEndDate = todayDate.ToString("G");
Eyal H
  • 991
  • 5
  • 22