使用java xml api将xml文档保存到文件

时间:2012-02-07 14:51:22

标签: c# java xml

我陷入了这个级别(在代码片段中不可编辑的Java和C#组合):

...
//then write results out to a file, which can then be used by XPF Application
         Document photosDoc = new Document();
         Element photosElement = new Element("photos", from pi in photos
                 select new XElement("photo",
                     new XElement("url", pi.PhotoUrl(false)),
                     new XElement("title", pi.Title))
             );
         photosDoc.Add(photosElement);
         photosDoc.Save("C:\\photos.xml");

我不知道如何转换这部分代码以将结果写入文件。我想将结果保存到xml文件中。

任何帮助?


在尝试将此C#代码转换为java代码时,我偶然发现了这个问题:

using System;
using System.Collections.Generic;
using System.Text;
System.Query;
using System.Xml.XLinq;
using System.Data.DLinq;
public class RSSImageFeed 
{
    private const string FLICKR_API_KEY = "c705bfbf75e8d40f584c8a946cf0834c";
    private const string MOST_RECENT = "http://www.flickr.com/services/rest/?method=flickr.photos.getRecent&api_key=" + FLICKR_API_KEY;
    private const string INTERESTING = "http://www.flickr.com/services/rest/?method=flickr.interestingness.getList&api_key=" + FLICKR_API_KEY;
    private const string ENTER_TAG = "http://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=" + FLICKR_API_KEY + "&tags=";
    private string url = MOST_RECENT;
    private int pageIndex = 0;
    private int columns = 5;
    private int rows = 2;
    private bool prevAvail = false;
    private bool nextAvail = false;


    public RSSImageFeed()
    {

    }

    public bool IsPrevAvail
    {
        get { return prevAvail; }
    }
    public bool IsNextAvail
    {
        get { return nextAvail; }
    }

    public int PageIndex
    {
        set { pageIndex = value; }
        get { return pageIndex; }
    }



    public bool LoadPictures(string searchType, string searchWord)
    {


        switch (searchType)
        {
            case "Most Recent":
                this.url=MOST_RECENT;
                break;
            case "Interesting":
                this.url=INTERESTING;
                break;
            case "By Search Word":
                this.url = ENTER_TAG + searchWord;
                break;
            default :
                this.url = MOST_RECENT;
                break;
        }

        try
        {
            var xraw = XElement.Load(url);
            var xroot = XElement.Parse(xraw.Xml);
            //select the RSS data from Flickr, and use standard LINQ projection
            //to store it within a new PhotoInfo which is an object of my own making
            var photos = (from photo in xroot.Element("photos").Elements("photo")
                select new PhotoInfo
                { 
                    Id = (string)photo.Attribute("id"),
                    Owner = (string)photo.Attribute("owner"),
                    Title = (string)photo.Attribute("title"),
                    Secret = (string)photo.Attribute("secret"),
                    Server = (string)photo.Attribute("server"),
                    Farm = (string)photo.Attribute("Farm"),
                }).Skip(pageIndex * columns * rows).Take(columns * rows);

            //set the allowable next/prev states
            int count = photos.Count();

            if (pageIndex == 0)
            {
                this.prevAvail = false;
                this.nextAvail = true;
            }
            else
            {
                this.prevAvail = true;
            }
            //see if there are less photos than sum(Columns * Rows) if there are less
            //cant allow next operation
            if (count < columns * rows)
            {
                this.nextAvail = false;
            }
            //then write results out to a file, which can then be used by XPF Application
            XDocument photosDoc = new XDocument();
            XElement photosElement = new XElement("photos", from pi in photos
                    select new XElement("photo",
                        new XElement("url", pi.PhotoUrl(false)),
                        new XElement("title", pi.Title))
                );
            photosDoc.Add(photosElement);
            photosDoc.Save(@"c:\photos.xml");
            return true;

        }
        catch (Exception ex)
        {
            return false;
        }
    }
}

这是我尝试将上面的C#代码转换为java代码:

import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;



public class FlickrFeed {

private  String FLICKR_API_KEY = "204e5627ea6626101221a5c7b4b0dd3a";
private  String MOST_RECENT = "http://www.flickr.com/services/rest/?method=flickr.photos.getRecent&api_key=" + FLICKR_API_KEY;
private  String INTERESTING = "http://www.flickr.com/services/rest/?method=flickr.interestingness.getList&api_key=" + FLICKR_API_KEY;
private  String ENTER_TAG = "http://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=" + FLICKR_API_KEY + "&tags=";
private String url = MOST_RECENT;
private int pageIndex = 0;
private int columns = 5;
private int rows = 2;
private boolean prevAvail = false;
private boolean nextAvail = false;

public enum SearchType
{
    Most_Recent, Interesting, By_Search_Word
}

public FlickrFeed()
{

}
public boolean IsPrevAvail()
{
    return prevAvail; 
}
public boolean IsNextAvail()
{
     return nextAvail; 
}
public int PageIndex(int value)
{
     pageIndex = value; 
     return pageIndex; 
}
public boolean LoadPictures( String searchWord)
{
    SearchType searchType = SearchType.By_Search_Word;

    switch (searchType)
    {
        case Most_Recent:
            this.url=MOST_RECENT;
            break;
        case Interesting:
            this.url=INTERESTING;
            break;
        case By_Search_Word:
            this.url = ENTER_TAG + searchWord;
            break;
        default :
            this.url = MOST_RECENT;
            break;
    }


     try
     {

        // var xraw = XElement.Load(url);
        // var xroot = XElement.Parse(xraw.Xml);

         DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
         URL Url = new URL(url);
         Document doc = builder.parse(Url.openStream());
         NodeList nodes = null;
         Element element = null;

         //select the RSS data from Flickr, and store it within a new PhotoInfo which is an object of my own making
         nodes = doc.getElementsByTagName("photo");
         for (int i = 0; i < nodes.getLength(); i++) {
             element = (Element) nodes.item(i);
        String Id =  (String)element.getAttribute("id");
             System.out.println("id:="+Id);
        String Owner=(String)element.getAttribute("owner");
             System.out.println("Owner:="+Owner);
        String Title =   (String)element.getAttribute("title");
             System.out.println("Title:="+Title);
        String  Secret=  (String)element.getAttribute("secret");
             System.out.println("Secret:="+Secret);
        String  Server=  (String)element.getAttribute("server");
             System.out.println("Server:="+Server);
        String  Farm=    (String)element.getAttribute("farm");
             System.out.println("Farm:="+Farm);
             System.out.println("ok: " + nodes.getLength());


         }
         /* photos = (from photo in xroot.Element("photos").Elements("photo")
             select new PhotoInfo
             { 
                 Id = (string)photo.Attribute("id"),
                 Owner = (string)photo.Attribute("owner"),
                 Title = (string)photo.Attribute("title"),
                 Secret = (string)photo.Attribute("secret"),
                 Server = (string)photo.Attribute("server"),
                 Farm = (string)photo.Attribute("Farm"),
             }).Skip(pageIndex * columns * rows).Take(columns * rows);*/

         //set the allowable next/prev states

        // int count = photos.Count();
         int count = nodes.getLength();
         if (pageIndex == 0)
         {
             this.prevAvail = false;
             this.nextAvail = true;
         }
         else
         {
             this.prevAvail = true;

         //see if there are less photos than sum(Columns * Rows) if there are less
         //cant allow next operation
         if (count < columns * rows)
         {
             this.nextAvail = false;
         }
         //then write results out to a file, which can then be used by XPF Application
         Document photosDoc = new Document();
         Element photosElement = new Element("photos", from pi in photos
                 select new XElement("photo",
                     new XElement("url", pi.PhotoUrl(false)),
                     new XElement("title", pi.Title))
             );
         photosDoc.Add(photosElement);
         photosDoc.Save("C:\\photos.xml");
         return true;

     }
     catch (Exception ex)
     {
         return false;
     }
     /**
         * Methode permettant de retourner ce que contient un noeud
         * @param _node le noeud principal
         * @param _path suite des noms des noeud sans espace separés par des "|"
         * @return un string contenant la valeur du noeud voulu
         */


}
public String readNode(Node _node, String _path) {

    String[] paths = _path.split("\\|");
    Node node = null;

    if (paths != null && paths.length > 0) {
        node = _node;

        for (int i = 0; i < paths.length; i++) {
            node = getChildByName(node, paths[i].trim());
        }
    }

    if (node != null) {
        return node.getTextContent();
    } else {
        return "";
    }
}
/**
 * renvoye le nom d'un noeud fils a partir de son nom
 * @param _node noeud pricipal
 * @param _name nom du noeud fils
 * @return le noeud fils
 */
public Node getChildByName(Node _node, String _name) {
    if (_node == null) {
        return null;
    }
    NodeList listChild = _node.getChildNodes();

    if (listChild != null) {
        for (int i = 0; i < listChild.getLength(); i++) {
            Node child = listChild.item(i);
            if (child != null) {
                if ((child.getNodeName() != null && (_name.equals(child.getNodeName()))) || (child.getLocalName() != null && (_name.equals(child.getLocalName())))) {
                    return child;
                }
            }
        }
    }
    return null;
}
public static void main(String[] args) {
    FlickrFeed f= new FlickrFeed();
    f.LoadPictures("upcoming:event");

}

}

3 个答案:

答案 0 :(得分:2)

我从未见过C# - &gt; Java转换工具。语法很简单,但框架非常不同。即使有工具,我也会强烈反对。它不是捷径,你最终得到的代码是不可读的,并没有利用目标语言。我认为重写代码是最好的方案。

答案 1 :(得分:1)

对于Linq部分,请尝试查看Quaere。小心,该项目处于早期阶段。

答案 2 :(得分:1)

您的代码看起来很像您在Java / C#中进行XML转换。我会使用XSL来进行转换。我认为它会使代码更清晰。

特别是这部分:

 Element photosElement = new Element("photos", from pi in photos
         select new XElement("photo",
                 new XElement("url", pi.PhotoUrl(false)),
                 new XElement("title", pi.Title))
 );

这正是XSL的目的。