문제
나 XmlDocument
java,으로 만들어졌 Weblogic XmlDocument
parser.
나는 바꿀의 콘텐츠에 태그를 이 XMLDocument
내 자신의 데이터를 삽입 또는 태그는 경우 그것은 없다.
<customdata>
<tag1 />
<tag2>mfkdslmlfkm</tag2>
<location />
<tag3 />
</customdata>
예를 들어 나는 삽입하려는 어떤 URL 을 위치에서 태그:
<location>http://something</location>
하지만 그렇지 않으면 떠날로 XML 입니다.
현재 사용 XMLCursor
:
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();
}
나를 찾으려고"빠른" xquery
방법은 이후 XmlDocument
가 execQuery
는 방법이지만,그것을 찾지 못한 매우 쉽습니다.
할 사람이 있는 것보다 더 좋은 방법이?그것은 보합니다.
해결책
는 방법에 대해 XPath 기반 접근법?내가 좋아하는 이 방법대로 논리는 슈퍼 이해하기 쉽습니다.코드가 꽤 많 self-documenting.
하는 경우 xml 문서를 사용할 수 있으로는 org.w3c.dom.Document object(으로 가장 파서는 반환),할 수 있는 다음과 같은 다음과 같다:
// 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 );
}
}
그리고 여기 도우미 방법 findNodes 는 XPath 검색합니다.
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 );
}
다른 팁
는 방법에 대한 객체 지향적 접근법?할 수 있습 deserialise XML 하는 개체의 위치를 설정 값을 객체에 다음 serialise 다시 XML.
XStream 이 정말 쉽습니다.
예를 들어,당신의 주체는 당신의 경우에는 CustomData(나를 사용하여 공공 필드를 유지하는 간단한 예제):
public class CustomData {
public String tag1;
public String tag2;
public String location;
public String tag3;
}
다음을 초기화 XStream:
XStream xstream = new XStream();
// if you need to output the main tag in lowercase, use the following line
xstream.alias("customdata", CustomData.class);
지금 당신은 구성할 수 있는 객체에서 XML,위치를 설정 필드에는 개체 다시 생성 XML:
CustomData d = (CustomData)xstream.fromXML(xml);
d.location = "http://stackoverflow.com";
xml = xstream.toXML(d);
그 소리는 어떻게 합니까?
알지 못하는 경우 스키마 XStream 솔루션은 대지 않습니다.최소 XStream 에 레이더,지금 유용하게 사용할 수 있습니다.
당신이 할 수 있어야 이와 query
도
fn:replace(string,pattern,replace)
나는 새로운 xquery 을 나 자신을 확인할 수 있습니다 고통스러운 질의어로 작업하지만,그것은 일이 잘되면 당신이 얻을 통해 최초 학습 곡선입니다.
나는 여전히 원하는 쉬운 방법이 있었다는으로 효율적인가요?