简体   繁体   中英

Copy a node from one xml to another

I need to copy the node from yahoo weather to my local xml file. 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? So each time I start the application, I want to write the node in my local 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. My xml will be like:

<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:

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.

XMLDocument Class provides methods to select nodes from a document.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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