[英]Copy specified child node from one xml file to another xml file in C#
[英]Copy a node from one xml to another
我需要将节点从yahoo weather复制到本地xml文件。 我得到了具有所有属性的节点
XmlNode node = xdoc.SelectSingleNode("/rss/channel/item/yweather:condition", ns);
我不知道如何在本地data.xml文件中写入相同的节点? 因此,每次启动应用程序时,我都想在本地xml中写入该节点。 由于yahoo中的节点会在一小时内更新,因此我还想检查本地xml中最后一个节点的值在yahoo天气中是否相同,在这种情况下,请不要写下来。 我的xml将是这样的:
<condition text="Cloudy" temp="4" date="Thu, 06 Feb 2014 4:00 pm CET" />
<condition text="Cloudy" temp="3" date="Thu, 06 Feb 2014 6:00 pm CET" />
等等。我不想重复。 我该怎么做?
使用Linq-To-Xml:
XElement rss = XElement.Parse("string xml feed");
XNamespace ns = "http://...";
XElement feed = rss.Descendants(ns + "condition").Last();
XElement file = XElement.Load("file");
XElement local = file.Descendants(ns + "condition").LastOrDefault();
if (feed.Attribute("date").Value != local.Attribute("date").Value)
local.AddAfterSelf(feed);
file.Save("file");
您必须检查边缘情况,例如,如果文件为空,则在本地为null,然后处理这种情况,即,将新的feed节点元素放在文件中的位置。
XMLDocument类提供了从文档中选择节点的方法。
使用它来选择包含您的条件的外部节点
public XmlNode SelectSingleNode(
string xpath,
XmlNamespaceManager nsmgr
)
然后使用xpath语句再次使用它,该语句包含您从Yahoo返回的属性。 如果不存在节点,则使用以下命令将您的节点添加到条件集合中
public virtual XmlNode CreateNode(
string nodeTypeString,
string name,
string namespaceURI
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.