Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从JAXB的XSD创建XML文件_Java_Xml_Xsd_Jaxb - Fatal编程技术网

Java 从JAXB的XSD创建XML文件

Java 从JAXB的XSD创建XML文件,java,xml,xsd,jaxb,Java,Xml,Xsd,Jaxb,我在使用JAXB从XSD创建XML文件时遇到问题。下面是用于创建XML文件的XSD文件。(注:由于保密原因,名称已被编辑) 这是输出 <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Test xmlns="http://ibm.org/seleniumframework"/> 如何让代码输出屏幕和屏幕标记及其属性,我不确定我做错了什么。您创建了Test和ScreensType的实例,但

我在使用JAXB从XSD创建XML文件时遇到问题。下面是用于创建XML文件的XSD文件。(注:由于保密原因,名称已被编辑)

这是输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
        <Test xmlns="http://ibm.org/seleniumframework"/>


如何让代码输出屏幕和屏幕标记及其属性,我不确定我做错了什么。

您创建了
Test
ScreensType
的实例,但在将它们编组为XML之前,决不设置它们的任何属性。下面是正确的代码

public void generateXml() throws JAXBException, IOException {
    Test test = new Test();
    ScreensType screens = new ScreensType();
    test.getOption1OrOption2OrOption3().add(screens);
    ScreenType screen = new ScreenType();
    screen.setName1("a");
    screen.setName2("b");
    screen.setName3("c");
    screens.getScreen().add(screen);

    File f = new File("new.xml");
    JAXBContext context= JAXBContext.newInstance("com.q1labs.qa.xmlgenerator.model.generatedxmlclasses");
    Marshaller jaxbMarshaller = context.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    jaxbMarshaller.marshal(test, f);
    jaxbMarshaller.marshal(test, System.out);
}
输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Test xmlns="http://ibm.org/seleniumframework">
    <Option3>
        <Screen name1="a" name2="b" name3="c"/>
    </Option3>
</Test>

经过几天的尝试,最终我能够使用下面给出的代码正确地从xsd创建xml。希望这有助于:

           String filename = "<filepath/filename>";

          final Document doc = loadXsdDocument(filename);

       //Find the docs root element and use it to find the targetNamespace
            final Element rootElem = doc.getDocumentElement();
            String targetNamespace = null;
            if (rootElem != null && rootElem.getNodeName().equals("xs:schema")) 
                       {
                targetNamespace = rootElem.getAttribute("targetNamespace");
            }


                        //Parse the file into an XSModel object
            XSModel xsModel = new XSParser().parse(filename);

                        //Define defaults for the XML generation
            XSInstance instance = new XSInstance();
            instance.minimumElementsGenerated = 1;
            instance.maximumElementsGenerated = 1;
            instance.generateDefaultAttributes = true;
            instance.generateOptionalAttributes = true;
            instance.maximumRecursionDepth = 0;
            instance.generateAllChoices = true;
            instance.showContentModel = true;
            instance.generateOptionalElements = true;

                        //Build the sample xml doc
                        //Replace first param to XMLDoc with a file input stream to write to file
            QName rootElement = new QName(targetNamespace, "<xsd file name>");
            XMLDocument sampleXml = new XMLDocument(new StreamResult(System.out), true, 4, null);
            instance.generate(xsModel, rootElement, sampleXml);
        } catch (TransformerConfigurationException e) 
                {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static Document loadXsdDocument(String inputName) {
        final String filename = inputName;

        final DocumentBuilderFactory factory = DocumentBuilderFactory
                .newInstance();
        factory.setValidating(false);
        factory.setIgnoringElementContentWhitespace(true);
        factory.setIgnoringComments(true);
        Document doc = null;

        try {
            final DocumentBuilder builder = factory.newDocumentBuilder();
            final File inputFile = new File(filename);
            doc = builder.parse(inputFile);
        } catch (final Exception e) {
            e.printStackTrace();
            // throw new ContentLoadException(msg);
        }

        return doc;
    }
stringfilename=”“;
最终文件doc=loadXsdDocument(文件名);
//查找docs根元素并使用它查找targetNamespace
final元素rootElem=doc.getDocumentElement();
字符串targetNamespace=null;
if(rootElem!=null&&rootElem.getNodeName().equals(“xs:schema”))
{
targetNamespace=rootElem.getAttribute(“targetNamespace”);
}
//将文件解析为XSModel对象
XSModel XSModel=new XSParser().parse(文件名);
//定义XML生成的默认值
XSInstance=新XSInstance();
instance.minimumElementsGenerated=1;
instance.maximumElementsGenerated=1;
instance.generateDefaultAttributes=true;
instance.generateOptions属性=true;
instance.maximumRecursionDepth=0;
instance.generateAllChoices=true;
instance.showContentModel=true;
instance.generateOptionalElements=true;
//构建示例xml文档
//将XMLDoc的第一个参数替换为要写入文件的文件输入流
QName rootElement=新的QName(targetNamespace,“”);
XMLDocument sampleXml=newxmldocument(newstreamresult(System.out)),true,4,null;
generate(xsModel、rootElement、sampleXml);
}捕获(TransformerConfiguration异常e)
{
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
公共静态文档loadXsdDocument(字符串inputName){
最终字符串文件名=inputName;
最终DocumentBuilderFactory=DocumentBuilderFactory
.newInstance();
工厂设置验证(假);
setIgnoringElementContentWhitespace(true);
factory.setIgnoringComments(true);
单据单据=空;
试一试{
final DocumentBuilder=factory.newDocumentBuilder();
最终文件输入文件=新文件(文件名);
doc=builder.parse(输入文件);
}捕获(最终异常e){
e、 printStackTrace();
//抛出新ContentLoadException(msg);
}
退货单;
}

基于您的代码,您几乎没有创建
屏幕
屏幕
变量,也没有对它们做任何操作。您仅封送
测试。你忘了
test.setOption3(screen)`或类似的东西了吗?这很有效!非常感谢!我是JAXB的新手,所以你帮了我很多忙。@Colin747-我很高兴能帮上忙。顺便说一句,我维护了一个JavaXML和JSON绑定博客,您可能会发现它很有用:这个答案的示例代码使用了。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Test xmlns="http://ibm.org/seleniumframework">
    <Option3>
        <Screen name1="a" name2="b" name3="c"/>
    </Option3>
</Test>
           String filename = "<filepath/filename>";

          final Document doc = loadXsdDocument(filename);

       //Find the docs root element and use it to find the targetNamespace
            final Element rootElem = doc.getDocumentElement();
            String targetNamespace = null;
            if (rootElem != null && rootElem.getNodeName().equals("xs:schema")) 
                       {
                targetNamespace = rootElem.getAttribute("targetNamespace");
            }


                        //Parse the file into an XSModel object
            XSModel xsModel = new XSParser().parse(filename);

                        //Define defaults for the XML generation
            XSInstance instance = new XSInstance();
            instance.minimumElementsGenerated = 1;
            instance.maximumElementsGenerated = 1;
            instance.generateDefaultAttributes = true;
            instance.generateOptionalAttributes = true;
            instance.maximumRecursionDepth = 0;
            instance.generateAllChoices = true;
            instance.showContentModel = true;
            instance.generateOptionalElements = true;

                        //Build the sample xml doc
                        //Replace first param to XMLDoc with a file input stream to write to file
            QName rootElement = new QName(targetNamespace, "<xsd file name>");
            XMLDocument sampleXml = new XMLDocument(new StreamResult(System.out), true, 4, null);
            instance.generate(xsModel, rootElement, sampleXml);
        } catch (TransformerConfigurationException e) 
                {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static Document loadXsdDocument(String inputName) {
        final String filename = inputName;

        final DocumentBuilderFactory factory = DocumentBuilderFactory
                .newInstance();
        factory.setValidating(false);
        factory.setIgnoringElementContentWhitespace(true);
        factory.setIgnoringComments(true);
        Document doc = null;

        try {
            final DocumentBuilder builder = factory.newDocumentBuilder();
            final File inputFile = new File(filename);
            doc = builder.parse(inputFile);
        } catch (final Exception e) {
            e.printStackTrace();
            // throw new ContentLoadException(msg);
        }

        return doc;
    }