Гость
Целевая тема:
Создать новую тему:
Автор:
Форумы / Java [игнор отключен] [закрыт для гостей] / помогите с xml / 5 сообщений из 5, страница 1 из 1
16.07.2007, 18:17:09
    #34662257
новичок xml
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
помогите с xml
подскажите пожалуйста, есть у меня XML файл,

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
<?xml version='1.0' encoding='UTF-8'   ?>

<s:config>
    <s id="001">
        <name value="001 s"></name>
        <image value="001image.jpg"></image>
    </s>
</s:config>



я хочу изменить, значения атрибута. Сначала вывожу весь файл, потом меняю значение,
в данном случае реализовал 2 мя способами , через Element и Node ,
если после изменения значения его вывести, то оно изменилось, а вот в сам файл изменения не попадают. в чём дело ?

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
 import  org.w3c.dom.*;

 import  javax.xml.parsers.DocumentBuilderFactory;
 import  javax.xml.parsers.DocumentBuilder;
 import  java.io.File;
 import  java.util.Enumeration;
 import  java.util.Vector;

 public   class  XmlRead {
    Element root =  null ;
     public  XmlRead(String fileName) {
        File xmlFile =  new  File(fileName);

        Document doc =  null ;
         try {

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();

            doc = db.parse(xmlFile);
            root = doc.getDocumentElement();
            System.out.println("root : "+root );
            NodeList children = root.getChildNodes();
            stepThrough(root);

        } catch  (Exception e) {
            System.out.print("Problem parsing the file: "+e.getMessage());
        }
    }
     private    void  stepThrough (Node start){
        System.out.println(start.getNodeName()+" = "+start.getNodeValue());
           if  (start.getNodeType() == start.ELEMENT_NODE)
              {
                NamedNodeMap startAttr = start.getAttributes();
                 for  ( int  i =  0 ;
                     i < startAttr.getLength();
                     i++) {
                  Node attr = startAttr.item(i);
                  System.out.println(" Attribute: "+ attr.getNodeName()
                      +" = "+attr.getNodeValue());
                }
              }

         for  (Node child = start.getFirstChild();
             child !=  null ;
             child = child.getNextSibling())
        {
          stepThrough(child);
        }
      }


 public   Boolean  updateService(String serviceId,String serviceName,
                                    String serviceImage){

           String packageId =  new  String();
             int  index =  0 ;  
             for  (Node child = root.getFirstChild(); child !=  null ; child = child.getNextSibling()){

                if  (child.getNodeName().equals("service"))
                 {
                   NamedNodeMap childAttr = child.getAttributes();
                    for  ( int  i =  0 ;i < childAttr.getLength();i++){
                       Node attr = childAttr.item(i);
                        if (attr.getNodeName().equals("id")&&(attr.getNodeValue().equals(serviceId))){
                            for  (Node childInside = child.getFirstChild();childInside !=  null ;
                                childInside = childInside.getNextSibling()){
                                if ((childInside.getNodeName().equals("name")&&
                                       (childInside.getNodeType() == childInside.ELEMENT_NODE))){
                                   childAttr = childInside.getAttributes();
                                    for  ( i =  0 ;i < childAttr.getLength();i++){
                                       Node attrCh = childAttr.item(i);
                                        if ((attrCh.getNodeName().equals("value"))){
                                            System.out.println(attrCh.getNodeValue());
                                           attrCh.setNodeValue(serviceName);
                                            System.out.println(attrCh.getNodeValue());

                                       }
                                   }

                               }
                            }
                        }
                    }
                }

            }
            NodeList orders = root.getElementsByTagName("service");
             for  ( int  orderNum =  0 ;orderNum < orders.getLength();orderNum++){
                Element thisOrder = (Element)orders.item(orderNum);
                NodeList orderItems = thisOrder.getElementsByTagName("image");
                 double  total =  0 ;
                 for  ( int  itemNum =  0 ;itemNum < orderItems.getLength();itemNum++) {
                     Element thisOrderItem = (Element)orderItems.item(itemNum);
                     System.out.println(thisOrderItem.getAttribute("value"));
                     thisOrderItem.setAttribute("value", serviceImage);
                     System.out.println(thisOrderItem.getAttribute("value"));

                }
            }

            return   new   Boolean (true);

       }
  public   static   void  main(String[] args){
        XmlRead hh =  new  XmlRead("c:/XmlParser/classes/Services.xml");

       hh.updateService("001","hhh","888");
        
    }
}

...
Рейтинг: 0 / 0
16.07.2007, 18:32:55
    #34662315
Leonidv
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
помогите с xml
В файл сохранить структуру XML-файла не забыли? DOM-дерево хранится в оперативной памяти и с файлом на диске работа не ведется.
...
Рейтинг: 0 / 0
16.07.2007, 18:55:11
    #34662363
помогите с xml
LeonidvВ файл сохранить структуру XML-файла не забыли? DOM-дерево хранится в оперативной памяти и с файлом на диске работа не ведется.

хм, видемо забыл, а точнее не нашёл, что такое есть, хотя думал , что что -то такое должно быть.

это делается каким -то методом или надо вывести весь документ в файл ? примерно как тут выводится на консоль:


Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
...
   public   static   void  main (String args[]) {
    File docFile =  new  File("orders.xml");
    Document doc =  null ;
    Document newdoc =  null ; 
     try  {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      doc = db.parse(docFile);
      newdoc = db.newDocument();
    }  catch  (Exception e) {
      System.out.print("Problem parsing the file: "+e.getMessage());
    }
...
    thisOrder.insertBefore(totalElement, thisOrder.getFirstChild());
  }
  Element newRoot = newdoc.createElement("processedOrders");
  NodeList processOrders = doc.getElementsByTagName("order");
   for  ( int  orderNum =  0 ;
        orderNum < processOrders.getLength();
        orderNum++) {
    Element thisOrder = (Element)processOrders.item(orderNum);
    Element customerid =
      (Element)thisOrder.getElementsByTagName("customerid")
        .item( 0 );
    String limit = customerid.getAttributeNode("limit").getNodeValue();
    String total = thisOrder.getElementsByTagName("total").item( 0 )
        .getFirstChild().getNodeValue();
     double  limitDbl =  new   Double (limit).doubleValue();
     double  totalDbl =  new   Double (total).doubleValue();
    Element newOrder = newdoc.createElement("order");
    Element newStatus = newdoc.createElement("status");
     if  (totalDbl > limitDbl) {
      newStatus.appendChild(newdoc.createTextNode("REJECTED"));
    }  else  {
      newStatus.appendChild(newdoc.createTextNode("PROCESSED"));
    }
    Element newCustomer = newdoc.createElement("customerid");
    String oldCustomer = customerid.getFirstChild().getNodeValue();
    newCustomer.appendChild(newdoc.createTextNode(oldCustomer));
    Element newTotal = newdoc.createElement("total");
    newTotal.appendChild(newdoc.createTextNode(total));
    newOrder.appendChild(newStatus);
    newOrder.appendChild(newCustomer);
    newOrder.appendChild(newTotal);
    newRoot.appendChild(newOrder);
  }
  newdoc.appendChild(newRoot);
  System.out.print(newRoot.toString());
...


...
Рейтинг: 0 / 0
16.07.2007, 22:37:32
    #34662588
y3u
y3u
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
помогите с xml
если у тебя есть дом, его можно слить в файл через Transformer, просто используй StreamResult ...
...
Рейтинг: 0 / 0
17.07.2007, 10:30:32
    #34663144
новичок xml
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
помогите с xml
y3uесли у тебя есть дом, его можно слить в файл через Transformer, просто используй StreamResult ...

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


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