2012-02-07 29 views
0

我被困在這個級別(在片段的Java和C#編譯非混合):保存XML文檔與Java XML API文件

... 
//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"); 

} 

}

+0

這一切都取決於你的圖書館。 – 2012-02-07 14:54:19

+6

查找java xml API。 – CodesInChaos 2012-02-07 14:54:30

+0

它看起來沒有任何相似之處。 Java XML庫與C#的工作方式有很大不同。這就是說,只需選擇一個並學習它。 – Servy 2012-02-07 14:57:42

回答

2

我從來沒有見過C# - > Java轉換工具。語法很簡單,但框架非常不同。即使有工具,我也會強烈反對。這不是一個快捷方式,你最終得到的代碼是不可讀的,並且不利用目標語言。我認爲重寫代碼將是最好的方案。

+0

很確定他試圖只用它作爲他的工具。 – Servy 2012-02-07 15:14:15

1

對於Linq部分,請嘗試查看Quaere。小心,該項目處於早期階段。

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被造的。