📄 any.java
字号:
// Create and insert a new <bar> element. Element fooElement = secondElementChild.getOwnerDocument().createElementNS("http://openuri.org","bar"); Node valueNode = fooElement.getOwnerDocument().createTextNode("some text"); fooElement.appendChild(valueNode); arrayOfAnyNode.insertBefore(fooElement, secondElementChild); System.out.println("Output: <arrayofany> has a new <bar> child element.\n"); System.out.println(rootDoc + "\n"); return validateXml(rootDoc); } /** * Edits incoming <root> XML to make the following changes: replace * <somelement> with its <stringlist> child; add a new <foo> * element as the second child of <arrayofany>. * * This method illustrates how you can use the selectPath method * to find an element defined as xs:any in schema, then use * XmlCursor instances to edit the XML. * * @param rootDoc An instance of the <root> XML document. * @return <code>true</code> if the editing XML is valid; * otherwise, <code>false</code>. */ public boolean editExistingDocWithSelectPath(RootDocument rootDoc) { String namespaceDecl = "declare namespace any='" + m_namespaceUri + "'; "; XmlCursor selectionCursor = rootDoc.getRoot().getArrayofany().newCursor(); // Save the cursor's position for later, then use XPath // and cursor movement to position the cursor at // the <stringlist> element. selectionCursor.push(); selectionCursor.selectPath(namespaceDecl + "$this//any:someelement/any:stringlist"); selectionCursor.toNextSelection(); // Create a new cursor and move it to the selection // cursor's <someelement> parent. Moving the // <stringlist> element to this position, displacing // the <someelement> downward, then removing the // <someelement> XML effectively replaces <someelement> // with <stringlist>. XmlCursor editCursor = selectionCursor.newCursor(); editCursor.toParent(); selectionCursor.moveXml(editCursor); editCursor.removeXml(); editCursor.dispose(); // Return the cursor to the <arrayofany> element so you // can do more editing. Then move the cursor to the second // child and insert a new element as second child. selectionCursor.pop(); selectionCursor.toFirstChild(); selectionCursor.toNextSibling(); selectionCursor.beginElement("foo", "http://openuri.org"); selectionCursor.insertChars("some text"); selectionCursor.dispose(); System.out.println("Output: <stringlist> has been promoted to replace \n" + "<someelement>, and there's a new <foo> element.\n"); System.out.println(rootDoc + "\n"); return validateXml(rootDoc); } /** * Like the code in the buildDocFromScratch method, this code * uses the XmlCursor to build XML piece by piece, building * out the Arrayofany instance it receives. * * @return A valid <arrayofany> element bound to an * Arrrayofany instance. */ private Arrayofany buildArrayOfAny(Arrayofany arrayOfAny) { // Create a simple <stringelement> and move it into place // under <arrayofany>. StringelementDocument stringElementDoc = StringelementDocument.Factory.newInstance(); stringElementDoc.setStringelement("some text"); XmlCursor childCursor = stringElementDoc.newCursor(); childCursor.toFirstContentToken(); // Add a cursor to mark the position at which the new child // XML will be moved. XmlCursor arrayCursor = arrayOfAny.newCursor(); arrayCursor.toNextToken(); childCursor.moveXml(arrayCursor); childCursor.dispose(); // Create a <someelement> that contains a <stringlist> // child element, then get the XmlObject representing the new // <stringlist>. Note that the XmlCursor.beginElement method // leaves the cursor between START and END tokens -- where // content can be placed. arrayCursor.beginElement("someelement", m_namespaceUri); arrayCursor.beginElement("stringlist", m_namespaceUri); arrayCursor.toPrevToken(); XmlObject stringList = arrayCursor.getObject(); // The cursor's no longer needed. arrayCursor.dispose(); // Create the <stringlist> element's value and set it. ListOfStrings stringListValue = buildListOfStrings(); if (stringListValue == null) { return null; } stringList.set(stringListValue); // Validate the new XML. if (!validateXml(arrayOfAny)) { return null; } return arrayOfAny; } /** * Creates an instance of the ListOfStrings complex type defined * in the schema. The instance returned by this method can be * inserted using either a set* operation or a cursor, as in * {@link #buildArrayOfAny()}. * * @return A valid instance of ListOfStrings. */ private ListOfStrings buildListOfStrings() { // Create an instance of the ListOfStrings complex type. ListOfStrings stringList = ListOfStrings.Factory.newInstance(); stringList.setId("001"); // Add two children for the instance's root. XmlString stringElement = stringList.addNewStringelement(); stringElement.setStringValue("string1"); stringElement = stringList.addNewStringelement(); stringElement.setStringValue("string2"); // Validate the new XML. if (!validateXml(stringList)) { return null; } return stringList; } /** * <p>Validates the XML, printing error messages when the XML is invalid. Note * that this method will properly validate any instance of a compiled schema * type because all of these types extend XmlObject.</p> * * <p>Note that in actual practice, you'll probably want to use an assertion * when validating if you want to ensure that your code doesn't pass along * invalid XML. This sample prints the generated XML whether or not it's * valid so that you can see the result in both cases.</p> * * @param xml The XML to validate. * @return <code>true</code> if the XML is valid; otherwise, <code>false</code> */ public static boolean validateXml(XmlObject xml) { boolean isXmlValid = false; // A collection instance to hold validation error messages. ArrayList validationMessages = new ArrayList(); // Validate the XML, collecting messages. isXmlValid = xml.validate( new XmlOptions().setErrorListener(validationMessages)); // If the XML isn't valid, print the messages. if (!isXmlValid) { printErrors(validationMessages); } return isXmlValid; } /** * Receives the collection containing errors found during * validation and print the errors to the console. * * @param validationErrors The validation errors. */ public static void printErrors(ArrayList validationErrors) { Iterator iter = validationErrors.iterator(); while (iter.hasNext()) { System.out.println(">> " + iter.next() + "\n"); } } /** * <p>Creates a File from the XML path provided in main arguments, then * parses the file's contents into a type generated from schema.</p> * <p/> * <p>Note that this work might have been done in main. Isolating it here * makes the code separately available from outside this class.</p> * * @param xmlFilePath A path to XML based on the schema in inventory.xsd. * @return An instance of a generated schema type that contains the parsed * XML. */ public XmlObject parseXml(String xmlFilePath) { File xmlFile = new File(xmlFilePath); XmlObject xml = null; try { xml = XmlObject.Factory.parse(xmlFile); } catch (XmlException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return xml; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -