gpt4 book ai didi

c# - 将属性添加到 XML 节点 C#

转载 作者:太空宇宙 更新时间:2023-11-03 12:20:46 25 4
gpt4 key购买 nike

我正在尝试向 XML 节点添加一个属性

实际值(value)

<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"?有人可以帮帮我吗。

最佳答案

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

requestDocument.CreateAttribute("HardshipEndDate", hardShipEndDate)

而且您不会在任何地方设置值(value)。而是这样做:

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

关于c# - 将属性添加到 XML 节点 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47421399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com