我正在尝试向XML节点添加属性
实际值
<Hardships>
<Hardship IsPrimary="true" EstimatedHardshipDuration="MEDIUM" HardshipReason="UNEMP" IsSeekingEmployment="Y" IsResolveableIn3MonthsVerbal="N" />
</Hardships>
节点更改后预期
<Hardships>
<Hardship IsPrimary="true" EstimatedHardshipDuration="MEDIUM" HardshipReason="UNEMP" IsSeekingEmployment="Y" IsResolveableIn3MonthsVerbal="N" HardshipEndDate="11/21/2017 12:00:00 AM/>
</Hardships>
我写了这样的代码
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));
我正在获得这样的输出
<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>
为什么我得到的属性就像他的“p7:HardshipEndDate =”“ xmlns:p7 =“2017-11-21T00:00:00.0000000-05:00”?有人可以帮助我。
答案 0 :(得分:1)
因为这里的第一个参数是元素名称,第二个参数是命名空间:
requestDocument.CreateAttribute("HardshipEndDate", hardShipEndDate)
你不能在任何地方设定价值。而是这样做:
var hardShipEndDate = todayDate.ToString("G");
var endDateAttr = requestDocument.CreateAttribute("HardshipEndDate");
endDateAttr.Value = hardShipEndDate;
HardshipDudeNode.Attributes.Append(endDateAttr);
请注意,对于xml,此类日期时间格式不常见。如果您不需要以特定格式生成日期,请更好地使用
// or XmlDateTimeSerializationMode.Local
var hardShipEndDate = XmlConvert.ToString(todayDate, XmlDateTimeSerializationMode.Utc);
答案 1 :(得分:0)
基本上您设置的格式不是您想要的格式。 根据这个link,你需要改变的是:
var hardShipEndDate = todayDate.ToString("G");