如何从 xsd 模式生成 xml?

发布于 2024-11-08 13:15:21 字数 143 浏览 0 评论 0原文

我有 xsd 模式..如何在 java 中以编程方式使用此模式来生成 xml..?它应该是动态的,意味着我可以给出任何模式。 有没有图书馆可以做同样的事情? 我已经看过其他帖子了,但不幸的是它不适合我..请提供旅游想法....??? 我没有找到任何方法来做同样的事情。

I am having xsd schema..How can I generate the xml by using this schema programmatically in java..? and it should be dynamic ,means I can give any schema.
Is there any library available to do same.?
I have alrady seen the other post also,but unfortunately it did not suit me.. please give tour ideas....???
I am not finding any approach to do same.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我也只是我 2024-11-15 13:15:21

XPath 不是生成 XML 的工具。恐怕您正在尝试使用错误的工具来实现您的目标。所以,我认为你的问题的答案是:你不能。

XPath is not a tool for generating XML. I'm afraid you're trying to accomplish your goal with the wrong tools. So, I think the answer to your question is: you can't.

夏尔 2024-11-15 13:15:21

看一下这个链接:

JAVA:使用 XPath 表达式构建 XML 文档

并浏览 XPath 标题下的此链接:

http://www.vogella.de /articles/JavaXML/article.html

我认为这应该对您有所帮助...:)

Take a look at this link :

JAVA: Build XML document using XPath expressions

And go through this link under the XPath heading :

http://www.vogella.de/articles/JavaXML/article.html

I think this should help you out...:)

忆悲凉 2024-11-15 13:15:21

以下代码根据您的需要执行验证,
还告诉您解析过程中发生错误的行号
您将需要以下 jar 来运行此代码,

唯一需要更改的代码是 validateSchema() 方法,其中请求响应参数需要替换为 xml 的字符串表示形式和 XSD 的字符串表示形式。

solver.jar、xml-apis.jar、serializer.jar、xercesImpl.jar

import org.apache.xerces.parsers.SAXParser;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XNIException;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Performs validation on XML based on the XSD. Overrides the
 * {@link SAXParser}.
 *
 *
 */
public class ValidateSchema extends SAXParser {

  /**
   * Container for current line and coloum number being parsed in the XML.
   */
  private XMLLocator locator;

  /**
   * Default public constructor.
   */
  public ValidateSchema() {
    super();
  }

  /**
   * Used for obtaining the {@link XMLLocator} locator object.
   */
  @Override
  public void startDocument(
      XMLLocator locator, String encoding, NamespaceContext namespaceContext, Augmentations augs)
      throws XNIException {
    this.locator = locator;
    super.startDocument(locator, encoding, namespaceContext, augs);
  }

  /**
   * Validates the XML against the provided XSD.
   *
   * @param req HttpServletRequest object.
   * @param resp HttpServletResponse object.
   * @throws IOException
   */
  public void validateSchema(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
    String content = req.getParameter("data");
    String selectbox = req.getParameter("selectbox");
    content = content.trim();

    // Convert the XML string to byte stream.
    InputStream is = new ByteArrayInputStream(content.getBytes());

    try {
      this.setFeature(Constants.VALIDATION_PROP, true);
      this.setFeature(Constants.SCHEMA_PROP, true);
      this.setFeature(Constants.DYNAMIC_PROP, true);
      this.setFeature(Constants.SCHEMA_CHECKING_PROP, true);
      if("1".equalsIgnoreCase(selectbox)) {
    this.setProperty(Constants.SCHEMA_LOC,"oem.xsd" );
      } else if("2".equalsIgnoreCase(selectbox)) {
    this.setProperty(Constants.SCHEMA_LOC,"carrier.xsd" );
      }

      Validator handler = new Validator();
      this.setErrorHandler(handler);

      InputSource isp = new InputSource();
      isp.setByteStream(is);
      isp.setEncoding("UTF-8");
      this.parse(isp);

      if (handler.validationError == true) {
    StringBuffer errorMessage = new StringBuffer(512);
    errorMessage
        .append("<div style='background: #ffebe6;border: 0px solid #ffe0d7;color:#c10000;height:60px;padding: 5px;'>")
        .append(Constants.INVALID_XML_DOCUMENT)
        .append(" LineNo: ")
        .append(handler.saxParseException.getLineNumber())
        .append(" ColumnNo: ")
        .append(handler.saxParseException.getColumnNumber())
        .append("<br/>")
        .append(handler.validationError)
        .append(handler.saxParseException.getMessage())
        .append("</div>");
    System.out.println( errorMessage );
      } else {
    StringBuffer validMsg = new StringBuffer(512);
    validMsg.append("<div style='background: #ebeff9;border: 0px solid #6b90da;height:60px;padding: 5px;'>")
    .append(Constants.VALID_XML_DOCUMENT).append("</div>");
    System.out.println( validMsg );
      }
    } catch (SAXException e) {
      StringBuffer errorMessage = new StringBuffer(512);
      errorMessage
      .append("<div style='background: #ffebe6;border: 0px solid #ffe0d7;color:#c10000;height:60px;padding: 5px;'>")
      .append(Constants.INVALID_XML_DOCUMENT)
      .append(" LineNo: ")
      .append(this.locator.getLineNumber())
      .append(" ColumnNo: ")
      .append(this.locator.getColumnNumber())
      .append(" <br/>")
      .append(e.getMessage())
      .append("</div>");
    System.out.println( errorMessage );
    } catch (Exception e) {
      StringBuffer errorMessage = new StringBuffer(512);
      errorMessage
      .append("<div style='background: #ffebe6;border: 1px solid #ffe0d7;color:#c10000;height:60px;padding: 5px;'>")
      .append(Constants.INVALID_XML_DOCUMENT)
      .append(" <br/>")
      .append(e.getMessage())
      .append("</div>");
     System.out.println( errorMessage );
    }
  }

  /**
   * Writes back the response to client.
   * 
   * @param msg Response message.
   * @param resp HttpServletResponse object.
   * @throws IOException
   */
  private void responseWrite(
      String msg, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/html");
    resp.getWriter().write(msg);
  }

  /**
   * Custom handler for Errors while parsing documents.
   */
  private class Validator extends DefaultHandler {
    public boolean validationError = false;
    public SAXParseException saxParseException = null;

    /**
     * @throws SAXException
     */
    @Override
    public void error(SAXParseException exception) throws SAXException {
      validationError = true;
      saxParseException = exception;
    }

    /**
     * @throws SAXException
     */
    @Override
    public void fatalError(SAXParseException exception) throws SAXException {
      validationError = true;
      saxParseException = exception;
    }

    /**
     * @throws SAXException
     */
    @Override
    public void warning(SAXParseException exception) throws SAXException {
    }
  }
}

Constants.Java 包含您需要指定的验证属性

public final class Constants {

public static final String VALIDATION_PROP = "http://xml.org/sax/features/validation";
public static final String SCHEMA_PROP = "http://apache.org/xml/features/validation/schema";
public static final String DYNAMIC_PROP = "http://apache.org/xml/features/validation/dynamic";
public static final String SCHEMA_CHECKING_PROP =
    "http://apache.org/xml/features/validation/schema-full-checking";
public static final String SCHEMA_LOC =
    "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation";
public static final String VALID_XML_DOCUMENT = "The above XML is valid.";
public static final String INVALID_XML_DOCUMENT = "The Document has error at:";

}

The following code performs validation as per your need,
and also tells you the line number where the error occurred during parsing
You will need following jars to run this code

Only code change needed is at validateSchema() method where request response args need to be replaced with a string representation of your xml and String representation of your XSD.

resolver.jar, xml-apis.jar, serializer.jar, xercesImpl.jar

import org.apache.xerces.parsers.SAXParser;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XNIException;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Performs validation on XML based on the XSD. Overrides the
 * {@link SAXParser}.
 *
 *
 */
public class ValidateSchema extends SAXParser {

  /**
   * Container for current line and coloum number being parsed in the XML.
   */
  private XMLLocator locator;

  /**
   * Default public constructor.
   */
  public ValidateSchema() {
    super();
  }

  /**
   * Used for obtaining the {@link XMLLocator} locator object.
   */
  @Override
  public void startDocument(
      XMLLocator locator, String encoding, NamespaceContext namespaceContext, Augmentations augs)
      throws XNIException {
    this.locator = locator;
    super.startDocument(locator, encoding, namespaceContext, augs);
  }

  /**
   * Validates the XML against the provided XSD.
   *
   * @param req HttpServletRequest object.
   * @param resp HttpServletResponse object.
   * @throws IOException
   */
  public void validateSchema(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
    String content = req.getParameter("data");
    String selectbox = req.getParameter("selectbox");
    content = content.trim();

    // Convert the XML string to byte stream.
    InputStream is = new ByteArrayInputStream(content.getBytes());

    try {
      this.setFeature(Constants.VALIDATION_PROP, true);
      this.setFeature(Constants.SCHEMA_PROP, true);
      this.setFeature(Constants.DYNAMIC_PROP, true);
      this.setFeature(Constants.SCHEMA_CHECKING_PROP, true);
      if("1".equalsIgnoreCase(selectbox)) {
    this.setProperty(Constants.SCHEMA_LOC,"oem.xsd" );
      } else if("2".equalsIgnoreCase(selectbox)) {
    this.setProperty(Constants.SCHEMA_LOC,"carrier.xsd" );
      }

      Validator handler = new Validator();
      this.setErrorHandler(handler);

      InputSource isp = new InputSource();
      isp.setByteStream(is);
      isp.setEncoding("UTF-8");
      this.parse(isp);

      if (handler.validationError == true) {
    StringBuffer errorMessage = new StringBuffer(512);
    errorMessage
        .append("<div style='background: #ffebe6;border: 0px solid #ffe0d7;color:#c10000;height:60px;padding: 5px;'>")
        .append(Constants.INVALID_XML_DOCUMENT)
        .append(" LineNo: ")
        .append(handler.saxParseException.getLineNumber())
        .append(" ColumnNo: ")
        .append(handler.saxParseException.getColumnNumber())
        .append("<br/>")
        .append(handler.validationError)
        .append(handler.saxParseException.getMessage())
        .append("</div>");
    System.out.println( errorMessage );
      } else {
    StringBuffer validMsg = new StringBuffer(512);
    validMsg.append("<div style='background: #ebeff9;border: 0px solid #6b90da;height:60px;padding: 5px;'>")
    .append(Constants.VALID_XML_DOCUMENT).append("</div>");
    System.out.println( validMsg );
      }
    } catch (SAXException e) {
      StringBuffer errorMessage = new StringBuffer(512);
      errorMessage
      .append("<div style='background: #ffebe6;border: 0px solid #ffe0d7;color:#c10000;height:60px;padding: 5px;'>")
      .append(Constants.INVALID_XML_DOCUMENT)
      .append(" LineNo: ")
      .append(this.locator.getLineNumber())
      .append(" ColumnNo: ")
      .append(this.locator.getColumnNumber())
      .append(" <br/>")
      .append(e.getMessage())
      .append("</div>");
    System.out.println( errorMessage );
    } catch (Exception e) {
      StringBuffer errorMessage = new StringBuffer(512);
      errorMessage
      .append("<div style='background: #ffebe6;border: 1px solid #ffe0d7;color:#c10000;height:60px;padding: 5px;'>")
      .append(Constants.INVALID_XML_DOCUMENT)
      .append(" <br/>")
      .append(e.getMessage())
      .append("</div>");
     System.out.println( errorMessage );
    }
  }

  /**
   * Writes back the response to client.
   * 
   * @param msg Response message.
   * @param resp HttpServletResponse object.
   * @throws IOException
   */
  private void responseWrite(
      String msg, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/html");
    resp.getWriter().write(msg);
  }

  /**
   * Custom handler for Errors while parsing documents.
   */
  private class Validator extends DefaultHandler {
    public boolean validationError = false;
    public SAXParseException saxParseException = null;

    /**
     * @throws SAXException
     */
    @Override
    public void error(SAXParseException exception) throws SAXException {
      validationError = true;
      saxParseException = exception;
    }

    /**
     * @throws SAXException
     */
    @Override
    public void fatalError(SAXParseException exception) throws SAXException {
      validationError = true;
      saxParseException = exception;
    }

    /**
     * @throws SAXException
     */
    @Override
    public void warning(SAXParseException exception) throws SAXException {
    }
  }
}

Constants.Java contains the validation properties that you need to specify

public final class Constants {

public static final String VALIDATION_PROP = "http://xml.org/sax/features/validation";
public static final String SCHEMA_PROP = "http://apache.org/xml/features/validation/schema";
public static final String DYNAMIC_PROP = "http://apache.org/xml/features/validation/dynamic";
public static final String SCHEMA_CHECKING_PROP =
    "http://apache.org/xml/features/validation/schema-full-checking";
public static final String SCHEMA_LOC =
    "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation";
public static final String VALID_XML_DOCUMENT = "The above XML is valid.";
public static final String INVALID_XML_DOCUMENT = "The Document has error at:";

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文