简体   繁体   English

向现有XML节点添加元素

[英]Adding element to existing XML node

Where am i going wrong??? 我要去哪里错了???

I have an xml file with OppDetails as a tag already as shown below 我已经有一个带有OppDetails作为标记的xml文件,如下所示

<OppDetails>
  <OMID>245414</OMID> 
  <ClientName>Best Buy</ClientName> 
  <OppName>International Rate Card</OppName> 
  <CTALinkType>AO,IO,MC,TC</CTALinkType> 
  </OppDetails>
  </OppFact>

Now i am trying to add another element to it but getting an error in AppendChild method please help 现在,我正在尝试向其中添加另一个元素,但是AppendChild方法中出现错误,请帮助

XmlNode rootNode = xmlDoc.SelectSingleNode("OppDetails");
XmlElement xmlEle = xmlDoc.CreateElement("CTAStartDate");
xmlEle.InnerText = ExcelUtility.GetCTAStartDate();
rootNode.AppendChild(xmlEle);
            xmlDoc.Save("C:\\test.xml");
XmlElement xmlEle = xmlDoc.DocumentElement["OppDetails"];
XmlElement eleNew = xmlDoc.CreateElement("CTAStartDate");
eleNew.InnerText = ExcelUtility.GetCTAStartDate();
xmlEle.AppendChild(eleNew);
xmlDoc.Save("C:\\test.xml");

It is hard to tell without a full sample, but a common reason for SelectNodes / SelectSingleNode returning null is xml namespaces. 没有完整的示例很难说,但是SelectNodes / SelectSingleNode返回null的常见原因是xml名称空间。 If you xml makes use of element namespaces, you'll probably need to use an XmlNamespaceManager along with your query, and define a suitable alias for the namespace you want. 如果xml使用元素名称空间,则可能需要与查询一起使用XmlNamespaceManager ,并为所需的名称空间定义合适的别名。

Is rootNode null ? rootNode是否为null

From MSDN on SelectSingleNode : SelectSingleNode MSDN

The first XmlNode that matches the XPath query or a null reference (Nothing in Visual Basic) if no matching node is found. 如果找不到匹配的节点,则第一个与XPath查询匹配的XmlNode或一个空引用(在Visual Basic中为Nothing)。

If rootNode is null , it indicates that the node could not be found, and trying to use the null rootNode would cause the exception you are seeing. 如果rootNodenull ,则表明找不到该节点,并且尝试使用null rootNode将导致您看到的异常。

The exception you've reported means that you have not located the root element. 您报告的异常意味着您尚未找到根元素。 When SelectSingleNode can't find the requested node, it returns null . SelectSingleNode找不到请求的节点时,它返回null You didn't check for that. 您没有检查。

Read root node and add the new element in to the root node. 读取根节点,然后将新元素添加到根节点中。 I think you are trying to append in XML document. 我认为您正在尝试将其附加到XML文档中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM