powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / Не компелируется DOM
12 сообщений из 12, страница 1 из 1
Не компелируется DOM
    #34246254
drews
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Добрый всем день.
Не компелируется код - не понимаю в чем подстава:

автор/*
* (C) Copyright IBM Corp. 2003. All rights reserved.
*
* US Government Users Restricted Rights Use, duplication or
* disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
* The program is provided "as is" without any warranty express or
* implied, including the warranty of non-infringement and the implied
* warranties of merchantibility and fitness for a particular purpose.
* IBM will not be liable for any damages suffered by you as a result
* of using the Program. In no event will IBM be liable for any
* special, indirect or consequential damages or lost profits even if
* IBM has been advised of the possibility of their occurrence. IBM
* will not be liable for any third party claims against you.
*/

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
* A sample DOM writer. This sample program illustrates how to
* traverse a DOM tree.
*/

public class DomOne
{
public void parseAndPrint(String uri)
{
Document doc = null;

try
{
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(uri);
if (doc != null)
printDomTree(doc);
}
catch (Exception e)
{
System.err.println("Sorry, an error occurred: " + e);
}
}

/** Prints the specified node, recursively. */
public void printDomTree(Node node)
{
int type = node.getNodeType();
switch (type)
{
// print the document element
case Node.DOCUMENT_NODE:
{
System.out.println("<?xml version=\"1.0\" ?>");
printDomTree(((Document)node).getDocumentElement());
break;
}

// print element and any attributes
case Node.ELEMENT_NODE:
{
System.out.print("<");
System.out.print(node.getNodeName());

NamedNodeMap attrs = node.getAttributes();
for (int i = 0; i < attrs.getLength(); i++)
printDomTree(attrs.item(i));

System.out.print(">");

if (node.hasChildNodes())
{
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++)
printDomTree(children.item(i));
}

System.out.print("</");
System.out.print(node.getNodeName());
System.out.print('>');

break;
}

// Print attribute nodes
case Node.ATTRIBUTE_NODE:
{
System.out.print(" " + node.getNodeName() + "=\"" +
((Attr)node).getValue() + "\"");
break;
}

// handle entity reference nodes
case Node.ENTITY_REFERENCE_NODE:
{
System.out.print("&");
System.out.print(node.getNodeName());
System.out.print(";");
break;
}

// print cdata sections
case Node.CDATA_SECTION_NODE:
{
System.out.print("<![CDATA[");
System.out.print(node.getNodeValue());
System.out.print("]]>");
break;
}

// print text
case Node.TEXT_NODE:
{
System.out.print(node.getNodeValue());
break;
}

case Node.COMMENT_NODE:
{
System.out.print("<!--");
System.out.print(node.getNodeValue());
System.out.print("-->");
break;
}

// print processing instruction
case Node.PROCESSING_INSTRUCTION_NODE:
{
System.out.print("<?");
System.out.print(node.getNodeName());
String data = node.getNodeValue();
{
System.out.print(" ");
System.out.print(data);
}
System.out.print("?>");
break;
}
}
} // printDomTree(Node)

/** Main program entry point. */
public static void main(String argv[])
{
if (argv.length == 0 ||
(argv.length == 1 && argv[0].equals("-help")))
{
System.out.println("\nUsage: java DomOne uri");
System.out.println(" where uri is the URI of the XML " +
"document you want to print.");
System.out.println(" Sample: java DomOne sonnet.xml");
System.out.println("\nParses an XML document, then writes " +
"the DOM tree to the console.");
System.exit(1);
}

DomOne d1 = new DomOne();
d1.parseAndPrint(argv[0]);
}
}


вот такая ошибка:

автор

Article.java:69: cannot resolve symbol
symbol : method addAttribute (org.jdom.Attribute)
location: class org.jdom.Element
carElement.addAttribute(new Attribute("vin", "123fhg5869705iop90"));

Article.java:88: cannot resolve symbol
symbol : method addAttribute (java.lang.String,java.lang.String)
location: class org.jdom.Element
carElement.addContent(new Element("license")

Article.java:149: cannot resolve symbol
symbol : constructor XMLOutputter (java.lang.String,boolean)
location: class org.jdom.output.XMLOutputter
XMLOutputter outputter = new XMLOutputter(" ", true);


Article.java:165: cannot resolve symbol
symbol : constructor XMLOutputter (java.lang.String,boolean)
location: class org.jdom.output.XMLOutputter
XMLOutputter outputter = new XMLOutputter(" ", true);

4 errors

кстати в другом примере если из строчки, например
XMLOutputter outputter = new XMLOutputter(" ", true);
сделать:
XMLOutputter outputter = new XMLOutputter();

то все проходит
...
Рейтинг: 0 / 0
Не компелируется DOM
    #34246862
Фотография Ruslan.Isbarov
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Может разница в версиях парсеров? Кстати, однажды с похожей проблемой сталкивался, вот только не вспомню сейчас какие парсеры использовал. Короче, код был написан с использованием одного парсера, а я к проекту прицепил джарники от другого (или другую версию, чертов склероз :) ). Любопытно, некоторые наименования классов совпадали, имена методов и т.п.

Напишите, какой парсер используете, дальше посмотрим что с этим можно сделать...
...
Рейтинг: 0 / 0
Не компелируется DOM
    #34247397
wessen
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Я бы начал с того, что приведенный класс называется DomOne, а приведенные ошибки возникли в классе Article. Причем в классе DomOne никакого dom4j вообще нет.

Похоже на то, что при компиляции класса Article используется не та версия dom4j.
...
Рейтинг: 0 / 0
Не компелируется DOM
    #34247596
drews
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Добрый день, Руслан.
Использую jdk 1.4.2.
xalan.jar
xercesImpl.jar
(как посмотреть версию я не знаю)
jdom я взял с www.jdom.org
...
Рейтинг: 0 / 0
Не компелируется DOM
    #34247610
drews
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
привет, wessen

да, действительно не совпадает
дико извиняюсь, вчера по ошбике не тот код скопировал.
вот как раз article :

авторimport java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;


/**
* This class runs all the example code from the article. There is a method
* for each listing. The listing that each method represents is listed in the
* javadoc for the method. This class also has a main method that will allow
* you to execute any of the listings. Run this class with no parameters to
* get usage information.
* This class was tested with:
* xerces version 1.3.0
* xalan version 2.0.1
* jdom version beta6
* jdk version 1.2
*
* @author Harry Evans (harry@tralfamadore.com)
* @author Wes Biggs (wes@tralfamadore.com)
*/
public class Article {

/**
* Read and parse an xml document from the file at xml/sample.xml.
* This method corresponds to the code in Listing 7.
* @return the JDOM document parsed from the file.
*/
public static Document readDocument() {
try {
SAXBuilder builder = new SAXBuilder();
Document anotherDocument = builder.build(new File("xml/sample.xml"));
return anotherDocument;
} catch(JDOMException e) {
e.printStackTrace();
} catch(NullPointerException e) {
e.printStackTrace();
}
return null;
}

/**
* This method creates a JDOM document with elements that represent the
* properties of a car.
* This method corresponds to Listing 2.
* @return a JDOM Document that represents the properties of a car.
*/
public static Document createDocument() {
// Create the root element
Element carElement = new Element("car");
//create the document
Document myDocument = new Document(carElement);
//add an attribute to the root element
carElement.addAttribute(new Attribute("vin", "123fhg5869705iop90"));

//add a comment
carElement.addContent(new Comment("Description of a car"));

//add some child elements
/*
* Note that this is the first approach to adding an element and
* textual content. The second approach is commented out.
*/
Element make = new Element("make");
make.addContent("Toyota");
carElement.addContent(make);
//carElement.addContent(new Element("make").addContent("Toyota"));

//add some more elements
carElement.addContent(new Element("model").addContent("Celica"));
carElement.addContent(new Element("year").addContent("1997"));
carElement.addContent(new Element("color").addContent("green"));
carElement.addContent(new Element("license")
.addContent("1ABC234").addAttribute("state", "CA"));

return myDocument;
}

/**
* This method accesses a child element of the root element of the
* document built in listing 2 with the createDocument method.
* This method corresponds to Listing 3.
* @param myDocument the JDOM document built from Listing 2
*/
public static void accessChildElement(Document myDocument) {
//some setup
Element carElement = myDocument.getRootElement();

//Access a child element
Element yearElement = carElement.getChild("year");

//show success or failure
if(yearElement != null) {
System.out.println("Here is the element we found: " +
yearElement.getName() + ". Its content: " +
yearElement.getText() + "\n");
} else {
System.out.println("Something is wrong. We did not find a year Element");
}
}

/**
* This method removes a child element from a document. The document
* should be of the format created in Listing 2.
* This method corresponds to Listin 4.
* @param myDocument the JDOM document built from Listing 2.
*/
public static void removeChildElement(Document myDocument) {
//some setup
System.out.println("About to remove the year element.\nThe current document:");
outputDocument(myDocument);
Element carElement = myDocument.getRootElement();

//remove a child Element
boolean removed = carElement.removeChild("year");

//show success or failure
if(removed) {
System.out.println("Here is the modified document without year:");
outputDocument(myDocument);
} else {
System.out.println("Something happened. We were unable to remove the year element.");
}
}

/**
* This method shows how to use XMLOutputter to output a JDOM document to
* the stdout.
* This method corresponds to Listing 5.
* @param myDocument the JDOM document built from Listing 2.
*/
public static void outputDocument(Document myDocument) {
try {
XMLOutputter outputter = new XMLOutputter(" ", true);
outputter.output(myDocument, System.out);
} catch (java.io.IOException e) {
e.printStackTrace();
}
}

/**
* This method shows how to use XMLOutputter to output a JDOM document to
* a file located at xml/myFile.xml.
* This method corresponds to Listing 6.
* @param myDocument the JDOM document built from Listing 2.
*/
public static void outputDocumentToFile(Document myDocument) {
//setup this like outputDocument
try {
XMLOutputter outputter = new XMLOutputter(" ", true);

//output to a file
FileWriter writer = new FileWriter("xml/myFile.xml");
outputter.output(myDocument, writer);
writer.close();

} catch(java.io.IOException e) {
e.printStackTrace();
}
}

/**
* This method takes a JDOM document in memory, an xsl file at xml/car.xsl,
* and outputs the results to stdout.
* This method corresponds to Listing 9.
* @param myDocument the JDOM document built from Listing 2.
*/
public static void executeXSL(Document myDocument) {
try {
TransformerFactory tFactory = TransformerFactory.newInstance();
// Make the input sources for the XML and XSLT documents
org.jdom.output.DOMOutputter outputter = new org.jdom.output.DOMOutputter();
org.w3c.dom.Document domDocument = outputter.output(myDocument);
javax.xml.transform.Source xmlSource = new javax.xml.transform.dom.DOMSource(domDocument);
StreamSource xsltSource = new StreamSource(new FileInputStream("xml/car.xsl"));
//Make the output result for the finished document
/*
* Note that here we are just going to output the results to the
* System.out, since we don't actually have a HTTPResponse object
* in this example
*/
//StreamResult xmlResult = new StreamResult(response.getOutputStream());
StreamResult xmlResult = new StreamResult(System.out);
//Get a XSLT transformer
Transformer transformer = tFactory.newTransformer(xsltSource);
//do the transform
transformer.transform(xmlSource, xmlResult);
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(TransformerConfigurationException e) {
e.printStackTrace();
} catch(TransformerException e) {
e.printStackTrace();
} catch(org.jdom.JDOMException e) {
e.printStackTrace();
}
}

/**
* Main method that allows the various methods to be used.
* It takes a single command line parameter. If none are
* specified, or the parameter is not understood, it prints
* its usage.
*/
public static void main(String argv[]) {
if(argv.length == 1) {
String command = argv[0];
if(command.equals("create")) outputDocument(createDocument());
else if(command.equals("access")) accessChildElement(createDocument());
else if(command.equals("remove")) removeChildElement(createDocument());
else if(command.equals("output")) outputDocument(createDocument());
else if(command.equals("file")) outputDocumentToFile(createDocument());
else if(command.equals("read")) outputDocument(readDocument());
else if(command.equals("xsl")) executeXSL(createDocument());
else {
System.out.println(command + " is not a valid option.");
printUsage();
}
} else {
printUsage();
}
}

/**
* Convience method to print the usage options for the class.
*/
public static void printUsage() {
System.out.println("Usage: Article [option] \n where option is one of the following:");
System.out.println(" create - create a document as shown in Listing 2");
System.out.println(" access - access a child element as shown in Listing 3");
System.out.println(" remove - remove a child element as shown in Listing 4");
System.out.println(" output - output a document to the console as shown in Listing 5");
System.out.println(" file - output a document to xml/myFile.xml as shown in Listing 6");
System.out.println(" read - parse a document from xml/sample.xml as shown in Listing 7");
System.out.println(" xsl - transform a document as shown in Listing 9");
}
}
...
Рейтинг: 0 / 0
Не компелируется DOM
    #34247646
Фотография Ruslan.Isbarov
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
drewsДобрый день, Руслан.
Использую jdk 1.4.2.
xalan.jar
xercesImpl.jar
(как посмотреть версию я не знаю)
jdom я взял с www.jdom.org
В комментарии написано:


* This class was tested with:
* xerces version 1.3.0
* xalan version 2.0.1
* jdom version beta6

Скачайте последние версии указанных библиотек.
...
Рейтинг: 0 / 0
Не компелируется DOM
    #34248089
drews
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Привет Руслан. Скачал последние библиотеки, установил. Но от этого легче не стало.
Научился смотреть версию парсера с помощью команды:

java org.apache.xalan.xslt.EnvironmentCheck

вот, что у меня:

автор#---- BEGIN writeEnvironmentReport($Revision: 1.14 $): Useful stuff found: ----
version.DOM.draftlevel=2.0fd
java.class.path=D:\jdk\lib;D:\jdk\lib\dom.jar;D:\jdk\lib\dom4j.jar;D:\jdk\lib\jdom.jar;D:\jdk\lib\sax.jar;D:\jdk\lib\xalan.jar;
version.JAXP=1.1
java.ext.dirs=C:\Program Files\Java\j2re1.4.2_10\lib\ext
version.xerces2=Xerces-J 2.9.0
version.xerces1=not-present
version.xalan2_2=Xalan Java 2.4.1
version.xalan1=not-present
version.ant=not-present
java.version=1.4.2_10
version.DOM=2.0
version.crimson=present-unknown-version
sun.boot.class.path=C:\Program Files\Java\j2re1.4.2_10\lib\rt.jar;C:\Program Files\Java\j2re1.4.2_10\lib\i18n.jar;C:\Program Files\Java\j2re1.4.2_10\lib\sunrsasign.jar;C:\Program Files\Java\j2re1.4.2_10\lib\jsse.jar;C:\Program Files\Java\j2re1.4.2_10\lib\jce.jar;C:\Program Files\Java\j2re1.4.2_10\lib\charsets.jar;C:\Program Files\Java\j2re1.4.2_10\classes
#---- BEGIN Listing XML-related jars in: foundclasses.java.class.path ----
dom.jar-path=D:\jdk\lib\dom.jar
dom.jar-apparent.version=dom.jar present-unknown-version
dom.jar-path=D:\jdk\lib\jdom.jar
dom.jar-apparent.version=dom.jar present-unknown-version
sax.jar-apparent.version=sax.jar present-unknown-version
sax.jar-path=D:\jdk\lib\sax.jar
xalan.jar-apparent.version=xalan.jar WARNING.present-unknown-version
xalan.jar-path=D:\jdk\lib\xalan.jar
#----- END Listing XML-related jars in: foundclasses.java.class.path -----
version.SAX=2.0
version.xalan2x=Xalan Java 2.4.1
#----- END writeEnvironmentReport: Useful properties found: -----
# YAHOO! Your environment seems to be OK.
...
Рейтинг: 0 / 0
Не компелируется DOM
    #34248119
Фотография Ruslan.Isbarov
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Значит дело еще хуже. Разработчики могли изменить API, скорее всего так и произошло. Выход:

- либо искать версии указанные в комментах
- либо взять этот класс и переписать его с использованием новых версий
...
Рейтинг: 0 / 0
Не компелируется DOM
    #34248141
wessen
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Дело не в ксерсесе и не в ксалане, их вообще лучше не трогать. Ошибки из-за dom4j, написано же, нужна версия beta6.
...
Рейтинг: 0 / 0
Не компелируется DOM
    #34248301
drews
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
не dom4j, а jdom - или это одно и тоже.
и вы думаете если я последний релиз поменяю на бета версию все заработает? как-то это странно - зачем тогда она вообще нужна, непонимаю
...
Рейтинг: 0 / 0
Не компелируется DOM
    #34248369
wessen
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
drewsне dom4j, а jdom - или это одно и тоже.

нет, не одно и то-же, это я напутал.
drews
и вы думаете если я последний релиз поменяю на бета версию все заработает?

проще наверное было скачать и проверить чем писать этот пост.
...
Рейтинг: 0 / 0
Не компелируется DOM
    #34249650
drews
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Ребята кто-нибудь вообще юзает jdom

Каким образом вы выводите поток в файл?
Эта конструкция сделана для того чтобы выходящий xml имел правильные отступы:

то есть не работает как раз org.jdom.output.XMLOutputter должным образом

ни так:

автор
XMLOutputter serializer = new XMLOutputter();
serializer.setIndent(" "); // use two space indent
serializer.setNewlines(true);
serializer.output(doc, System.out);


ни так:

автор XMLOutputter serializer = new XMLOutputter(" ", true);
serializer.output(doc, System.out);

ошбика:

cannot resolve symbol
symbol : constructor XMLOutputter (java.lang.String,boolean)
location: class org.jdom.output.XMLOutputter

У меня такое впечатление что не находится МЕТОД для обработки

что вы об этом думаете?
...
Рейтинг: 0 / 0
12 сообщений из 12, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Не компелируется DOM
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]