Ahojte, vie niekto sposob ako zmenit v xml hodnotu elementu pomocou Java a xpath?
Niekde som aj nasiel na nete metodu setValue() ale nezafungovalo to... konkretne:
<product>
<nazov>Panasonic</nazov>
</product>
ako tu zmenim Panasonic na BENQ
Skusal som to takto: http://www.java2s.com/Tutorial/Java/0440__XML/GetandsetvaluethroughXPath.htm
nejak to upravit pretoze v tom priklade sa meni len atribut elementu..
Dakujem za rady:-)
PS napadlo ma aj ze vytvorim novy element a potom tento zmazem a pod... ale nejak to nejde...
Fórum › Java
Zmena hodnoty elementu v XML

To liborb : nejde to
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = documentBuilder.parse(new File("produkty.xml"));
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
Node textNode = (Node)xPath.evaluate("/product/nazov/text()", document, XPathConstants.NODE);
textNode.setNodeValue("BENQ");
System.out.println("Je to OK");
cele to mam takto, este mi to napise na konzolu:Je to OK cize to ani nejde do vynimky ani nic take... ale ten text neprepise... netreba to xml nejak odomknut alebo co?
produkty.xml vyzera takto
<?xml version="1.0" encoding="utf-8" ?>
<product>
<nazov>Panasonic</nazov>
</product>
ja to samozrejme robim ako iny programik kde budem do xml ukladat niektore osobne nastavenia uzivatela, co by sa dalo urobit aj cez txt ale xml je krajsie:-)
To vlado0991 : uz som na to prisiel :
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(
new InputSource("produkty.xml"));
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList) xpath.evaluate("/product/nazov", doc,
XPathConstants.NODESET);
for (int idx = 0; idx < nodes.getLength(); idx++) {
nodes.item(idx).setTextContent(hodnota);
}
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(new DOMSource(doc), new StreamResult(new File("produkty.xml")));
kde String hodnota je nova hodnota (napr. BENQ)
vlastny tranformujem povodne xml do noveho (ale s rovnakym nazvom:-) )

Přidej příspěvek
Ano, opravdu chci reagovat → zobrazí formulář pro přidání příspěvku
×Vložení zdrojáku
×Vložení obrázku
×Vložení videa
































Uživatelé prohlížející si toto vlákno
Podobná vlákna
Vkládání elementu z XML do XHTML — založil Míša
XML projekt 50 elementů, 10 atributů — založil MariSl
Vyhledání a nahrazení elementu v XML přes xPath — založil Standa
Zmena onchange elementu — založil Anonym
Hromadná zmena elementu rovnakej class — založil echo88
Moderátoři diskuze