简体   繁体   English

将一个节点从一个xml复制到另一个

[英]Copy a node from one xml to another

I need to copy the node from yahoo weather to my local xml file. 我需要将节点从yahoo weather复制到本地xml文件。 I got the node with all its attributes with 我得到了具有所有属性的节点

XmlNode node = xdoc.SelectSingleNode("/rss/channel/item/yweather:condition", ns);

What I don't know is how to write the same node in my local data.xml file? 我不知道如何在本地data.xml文件中写入相同的节点? So each time I start the application, I want to write the node in my local xml. 因此,每次启动应用程序时,我都想在本地xml中写入该节点。 Because the node in yahoo is updated like in an hour, I want also to check if the values from the last node in my local xml is the same in the yahoo weather, in that case do not write it down. 由于yahoo中的节点会在一小时内更新,因此我还想检查本地xml中最后一个节点的值在yahoo天气中是否相同,在这种情况下,请不要写下来。 My xml will be like: 我的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" />

etc. I don't want to have duplicates. 等等。我不想重复。 How can I do it? 我该怎么做?

Using Linq-To-Xml: 使用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");

You'll have to check for edge cases, such as null in local if your file is empty, and handle that case, ie where to put the new feed node element in the file. 您必须检查边缘情况,例如,如果文件为空,则在本地为null,然后处理这种情况,即,将新的feed节点元素放在文件中的位置。

XMLDocument Class provides methods to select nodes from a document. XMLDocument类提供了从文档中选择节点的方法。

Use this to select the outer node that contains your conditions 使用它来选择包含您的条件的外部节点

public XmlNode SelectSingleNode(
    string xpath,
    XmlNamespaceManager nsmgr
)

Then use it again using an xpath statement containing the attributes you have returned from Yahoo. 然后使用xpath语句再次使用它,该语句包含您从Yahoo返回的属性。 If no node exists then just add your node to the collection of conditions using 如果不存在节点,则使用以下命令将您的节点添加到条件集合中

public virtual XmlNode CreateNode(
    string nodeTypeString,
    string name,
    string namespaceURI
)

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

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