将属性添加到 XML 节点 C#

Adding Attribute to XML node C#

我正在尝试将属性添加到 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" ?谁能帮帮我。

基本上您设置的格式并不是您想要的格式。 根据这个 link 你需要改变的是:

var hardShipEndDate = todayDate.ToString("G");

因为这里的第一个参数是元素名称,第二个是命名空间:

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);