【发布时间】:2011-03-15 14:12:02
【问题描述】:
我目前正在处理一个 XML 请求,并且正在尝试创建一个回复文档,该文档在调用中具有多个同名子节点,所以我想要返回的是:
<Reply Document>
<ConfirmationItem name = "One">
<ItemDetail />
</ConfirmationItem>
<ConfirmationItem name = "Two">
<ItemDetail />
</ConfirmationItem>
...
<ConfirmationItem name = "Twenty">
<ItemDetail />
</ConfirmationItem>
</Reply Document>
我做了一些研究,发现了这个线程:XmlReader AppendChild is not appending same child value,其中接受的答案是 OP 必须创建新元素才能附加到末尾而不是覆盖第一个。
我的原始代码如下,它从传入的请求创建 XmlNode 并将结果附加到 XmlDocument 本身:
//p_transdoc is the XmlDocument that holds all the items to process.
XmlNodeList nodelst_cnfrm = p_transdoc.SelectNodes("//OrderRequest");
foreach (XmlNode node in nodelst_cnfrm)
{
//this is just an XML Object
XmlNode node_cnfrm_itm = this.CreateElement("ConfirmationItem");
node_cnfrm_itm.Attributes.Append(this.CreateAttribute("name")).InnerText = p_transdoc.Attributes["name"].InnerText;
XmlNode node_itmdtl = this.CreateElement("ItemDetail");
node_cnfrm_itm.AppendChild(node_itmdtl);
//xml_doc is the return XML request
xml_doc.AppendChild(node_cnfrm_itm);
}
因此,在阅读了该线程和答案后,我尝试更改代码以使用新的 XmlElement 每次通过。
//p_transdoc is the XmlDocument that holds all the items to process.
XmlNodeList nodelst_cnfrm = p_transdoc.SelectNodes("//OrderRequest");
foreach (XmlNode node in nodelst_cnfrm)
{
XmlElement node_cnfrm_itm = new XmlElement();
node_cnfrm_itm = this.CreateElement("ConfirmationItem");
node_cnfrm_itm.Attributes.Append(this.CreateAttribute("name")).InnerText = p_transdoc.Attributes["name"].InnerText;
XmlElement node_itmdtl = new XmlElement();
node_itmdtl = this.CreateElement("ItemDetail");
node_cnfrm_itm.AppendChild(node_itmdtl);
//xml_doc is the return XML request
xml_doc.AppendChild(node_cnfrm_itm);
}
但这不仅不起作用,还会返回服务器错误。所以我来找你帮忙了。现在这段代码只返回一个 ConfirmationItem。我如何能够将 ConfirmationItem 附加到 Document 的末尾而不是覆盖它,以便能够返回与发送的一样多的内容?
(我应该指出,为了便于阅读、简化和减少混乱,这段代码已经过大量格式化。任何印刷错误纯粹是因为提问者在有效校对方面的内部失败)。
【问题讨论】:
-
'this'是什么样的对象?