2010-10-11 72 views
5

我有以下的Java代码,我需要把这些转换成C#,请帮助我..的SAXParser相当于在C#

public class Configuration { 

    private ConfigContentHandler confHandler; 

    public Configuration() { 
    } 

    public boolean parseConfigFile() throws Exception { 
    boolean bReturn = true; 

    SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); 

    System.out.println("*** Start parsing"); 

    try { 
     confHandler = new ConfigContentHandler(100); 
     // Configuration file must be located in main jar file folder 

     // Set the full Prosper file name 
     String sConfigFile = "configuration.xml"; 

     // Get abstract (system independent) filename 
     File fFile = new File(sConfigFile); 

     if (!fFile.exists()) { 
      System.out.println("Could not find configuration file " + sConfigFile + ", trying input parameters."); 
      bReturn = false; 
     } else if (!fFile.canRead()) { 
      System.out.println("Could not read configuration file " + sConfigFile + ", trying input parameters."); 
      bReturn = false; 
     } else { 
      parser.parse(fFile, confHandler); 
     } 

    } catch (ArrayIndexOutOfBoundsException e) { 
     System.out.println("Input error."); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    System.out.println("*** End parsing"); 
    return bReturn; 
    } 

感谢

回答

7

C#原生XML解析器XmlReader不支持SAX是只进。您可以查看this article,其中介绍了一些具体的观点。你可以simulate a SAX parser using XmlReader。如果它不适合你的需求,你也可以使用XDocument这是一个不同的API来处理.NET中的XML文件。因此,为了得出结论,.NET框架中没有内置XML解析器,因此如果您确实需要事件驱动解析器,则可能需要使用第三方库或COM Interop到MSXML才能实现此目的。

+0

该操作只想读取配置,但为了其他对SAX解析感兴趣的人:一般情况下*不能*用XmlReader模拟SAX解析器,因为SAX的概念不同:SAX给我一个“open元素标签“,即使文档格式不正确并且从不关闭。 XmlReader仅在完成读取时才会给我整个子树,因此必须完整。还有另一个SAX端口[这里](https://github.com/rasmusjp/sax.net),但我不确定它的价值。 – John 2015-05-10 10:07:17