【问题标题】:SAXParser equivalent in C#C# 中的 SAXParser 等效项
【发布时间】:2023-03-09 19:46:02
【问题描述】:

我有下面的java代码,我需要用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;
  }

谢谢

【问题讨论】:

    标签: c# saxparser


    【解决方案1】:

    C# 原生 XML 解析器 XmlReader 不支持 SAX 并且只转发。你可以看看this article 提出一些关于它的具体观点。你可以simulate a SAX parser using XmlReader。如果它不满足您的需求,您还可以使用XDocument,它是用于在 .NET 中处理 XML 文件的不同 API。因此得出结论,.NET 框架中没有内置推送 XML 解析器,因此如果您确实需要事件驱动的解析器,您可能需要使用第三方库或 COM Interop to MSXML 来实现这一点。

    【讨论】:

    • op 只想读取配置,但为了其他对 SAX 解析感兴趣的人的利益:您通常可以使用 XmlReader 模拟 SAX 解析器,因为 SAX 的概念是不同:SAX 给了我一个“开放元素标签”,即使文档格式错误并且它永远不会关闭。 XmlReader 仅在完成读取时才给我整个子树,因此必须是完整的。还有另一个 SAX 端口here,但我不确定它的价值。
    【解决方案2】:

    我过去在两个项目中成功地使用了 SAX for .NET。 http://saxdotnet.sourceforge.net/

    【讨论】:

      猜你喜欢
      • 2012-07-31
      • 2010-10-20
      • 2013-12-09
      • 1970-01-01
      • 2014-05-08
      • 2013-05-24
      • 2012-09-15
      • 1970-01-01
      相关资源
      最近更新 更多