2017-12-30 48 views
0

구조는 : 나는 그것에 할당 된 다른 속성과 내의 다른 요소와 다른 로그인 요소를 쓸 수있는 자바 코드를 추가하는 것을 시도하고있다특정 속성을 가진 특정 요소에서 XML 문서에 쓰는 방법은 무엇입니까? 내 XML 문서의

<?xml version="1.0" encoding="UTF-8"?> 
<PasswordVault> 
    <User id="1"> 
    <Log LOG="1"> 
     <AccountType>a</AccountType> 
     <Username>a</Username> 
     <Password>a</Password> 
     <E-mail>a</E-mail> 
    </Log> 
    <Log Log="2"> 
     <AccountType>b</AccountType> 
     <Username>b</Username> 
     <Password>b</Password> 
     <E-mail>b</E-mail> 
    </Log> 
    </User> 
    <User id="2"> 
    <Log LOG="2"> 
     <AccountType>a</AccountType> 
     <Username>a</Username> 
     <Password>a</Password> 
     <E-mail>a</E-mail> 
    </Log> 
    </User> 
</PasswordVault> 

. 그러나 id = "2"인 속성 인 올바른 사용자 요소 내에 있어야합니다. JDOM과 SAX를 사용하고 있지만이 작업을 수행하는 방법을 보여주는 자습서를 찾을 수없는 것 같습니다.

public static void editXML(String inpName,String inpPassword,String inpEmail,String inpAccountType) { 
     try { 

      SAXBuilder builder = new SAXBuilder(); 
      File xmlFile = new File("FILE PATH"); 

      Document doc = (Document) builder.build(xmlFile); 
      Element rootNode = doc.getRootElement(); 

      // PROBLEM HERE - dont know how to find element by specific attribute 
      Element user = rootNode.getChild("User"); 



      // add new element 
      // hard coded just to test it 
      Element newLog = new Element("Log").setAttribute("Log","1"); 

      // new elements 
      Element accountType = new Element("AccountType").setText(inpAccountType); 
      newLog.addContent(accountType); 

      Element name = new Element("Username").setText(inpName); 
      newLog.addContent(name); 

      Element password = new Element("Password").setText(inpPassword); 
      newLog.addContent(password);     

      Element email = new Element("E-mail").setText(inpEmail); 
      newLog.addContent(email); 

      user.addContent(newLog); 

      XMLOutputter xmlOutput = new XMLOutputter(); 

      // display nice nice 
      xmlOutput.setFormat(Format.getPrettyFormat()); 
      xmlOutput.output(doc, new FileWriter("FILE PATH")); 

      // xmlOutput.output(doc, System.out); 

      System.out.println("File updated!"); 
      } catch (IOException io) { 
      io.printStackTrace(); 
      } catch (JDOMException e) { 
      e.printStackTrace(); 
      } 


} 

나는 Xpath에 대해 머리를 가졌지 만 매우 익숙하지 않아 내 상황과 관련하여 온라인을 많이 찾을 수 없었다.

답변

1

아래 코드로 id 속성 2를 사용하여 User 요소를 필터링 할 수 있습니다. 당신은 사용자 요소가이가 내 솔루션에서 구현 될 수있는 방법을

Element user = null; 
if (userNode.isPresent()) { 
    user = userNode.get(); 
} else { 
    //handle failure 
} 

if (user != null) { 
    // create new elements and rest of the logic 
} 
+0

아래와 같이 존재하는 경우 확인해야 그 후

final Optional<Element> userNode = rootNode.getChildren("User").stream() .filter(user -> "2".equals(user.getAttributeValue("id"))).findFirst(); 

? – Harshmellow

+0

대답을 –

+1

고마워, 그 작품 : D 조 – Harshmellow