2008-08-19 2 views
3

나는 Weblogic XmlDocument 파서로 작성한 XmlDocument을 java에 가지고 있습니다.XmlDocument에서 XML 태그 삽입/바꾸기

XMLDocument에있는 태그의 콘텐츠를 내 데이터로 바꾸거나 태그가없는 경우 해당 태그를 삽입하고 싶습니다.

<customdata> 
    <tag1 /> 
    <tag2>mfkdslmlfkm</tag2> 
    <location /> 
    <tag3 /> 
</customdata> 

나는 예를 들어, 위치 태그의 일부 URL을 삽입 할 : 그대로

<location>http://something</location> 

하지만 그렇지 않으면 XML을 둡니다.

XmlObject xmlobj = XmlObject.Factory.parse(a.getCustomData(), options); 
    XmlCursor xmlcur = xmlobj.newCursor(); 

    while (xmlcur.hasNextToken()) { 
     boolean found = false; 
     if (xmlcur.isStart() && "schema-location".equals(xmlcur.getName().toString())) { 
     xmlcur.setTextValue("http://replaced"); 
     System.out.println("replaced"); 
     found = true; 
     } else if (xmlcur.isStart() && "customdata".equals(xmlcur.getName().toString())) { 
     xmlcur.push(); 
     } else if (xmlcur.isEnddoc()) { 
     if (!found) { 
      xmlcur.pop(); 
      xmlcur.toEndToken(); 
      xmlcur.insertElementWithText("schema-location", "http://inserted"); 
      System.out.println("inserted"); 
     } 

     } 
     xmlcur.toNextToken(); 
    } 

내가 XmlDocumentexecQuery 방법이 있기 때문에이 작업을 수행하는 "빠른"xquery 방법을 찾아야했지만, 매우 쉽게 찾을 수 없습니다 :

현재 나는 XMLCursor 사용합니다.

아무에게도 이보다 좋은 방법이 있습니까? 그것은 약간 정교하게 보인다.

답변

4

XPath 기반 방식은 어떻습니까? 논리가 이해하기 쉽도록이 접근법을 좋아합니다. 이 코드는 거의 자체 문서화입니다. 당신의 XML 문서 (대부분 파서 반환으로), 당신은 다음과 같은 것을 할 수있는 org.w3c.dom.Document 개체로 당신에게 사용할 수있는 경우

: 여기

// get the list of customdata nodes 
NodeList customDataNodeSet = findNodes(document, "//customdata"); 

for (int i=0 ; i < customDataNodeSet.getLength() ; i++) { 
    Node customDataNode = customDataNodeSet.item(i); 

    // get the location nodes (if any) within this one customdata node 
    NodeList locationNodeSet = findNodes(customDataNode, "location"); 

    if (locationNodeSet.getLength() > 0) { 
    // replace 
    locationNodeSet.item(0).setTextContent("http://stackoverflow.com/"); 
    } 
    else { 
    // insert 
    Element newLocationNode = document.createElement("location"); 
    newLocationNode.setTextContent("http://stackoverflow.com/"); 
    customDataNode.appendChild(newLocationNode); 
    } 
} 

을 그리고는 도우미 메서드입니다 XPath 검색을 수행하는 findNodes.

private NodeList findNodes(Object obj, String xPathString) 
    throws XPathExpressionException { 

    XPath xPath = XPathFactory.newInstance().newXPath(); 
    XPathExpression expression = xPath.compile(xPathString); 
    return (NodeList) expression.evaluate(obj, XPathConstants.NODESET); 
} 
0

당신은 내가 나 자신을 XQuery에 새로운 오전과 내가 함께 작업하는 고통스러운 쿼리 언어로 발견

fn:replace(string,pattern,replace) 

시도 query

이 작업을 수행 할 수 있어야하지만,이 작업을 수행 조용히 잘 일단 초기 학습 곡선을 극복.

나는 더 쉬운 방법이 있었으면 좋겠다.

+1

replace는 문서를 수정하지 않고 단지 문자열의 텍스트 항목을 대체하고 문자열을 반환합니다. –

1

개체 지향 접근법은 어떻습니까? XML을 객체로 역 직렬화하여 객체의 위치 값을 설정 한 다음 XML로 다시 직렬화 할 수 있습니다.

XStream은 정말 쉽습니다. 당신이 XStream을 초기화 다음

public class CustomData { 
    public String tag1; 
    public String tag2; 
    public String location; 
    public String tag3; 
} 

:

예를 들어, (나는 간단한 예제를 유지하기 위해 공공 필드를 사용하고 있습니다) 귀하의 경우에서는 CustomData있는 주요 객체를 정의 할

XStream xstream = new XStream(); 
// if you need to output the main tag in lowercase, use the following line 
xstream.alias("customdata", CustomData.class); 

CustomData d = (CustomData)xstream.fromXML(xml); 
d.location = "http://stackoverflow.com"; 
xml = xstream.toXML(d); 
:

이제 XML을, XML에서 개체를 구성하는 개체에 위치 필드를 설정하고 재생성 할 수 있습니다

어떻게 들리는가요?

1

스키마를 모르는 경우 XStream 솔루션은 아마도 갈 길이 없습니다. 적어도 XStream은 현재 귀하의 레이더에 있으며, 앞으로는 편리하게 사용할 수 있습니다!

관련 문제