Regex com XML?

tem como ler o xml verificar a tag ReferencedEntitlement e verificar 4857230038 se o numero é final 0038, caso isso seja afirmativo apagar a tag inteira

eu consigo fazer isso com regex

 <ReferencedEntitlement id="4504a142-d39c-4af4-8314-62b90feac165">
        <CreationDate>2011-05-20T14:12:31.323Z</CreationDate>
        <ProductId>c856c318-51e1-468a-b950-8bc3ed3e5b89</ProductId>
        <CustomerId>4857230038</CustomerId>
      </ReferencedEntitlement>

obrigado

Acho que você pode tentar fazer isso com Dom4j + XPath para achar o nó e fazer a remoção…

[code]
package snippet;

import java.io.IOException;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class Snippet {

public static void main(String[] args) throws IOException,
		DocumentException {
	String xml = "<root>" +
			"<ReferencedEntitlement id=\"4504a142-d39c-4af4-8314-62b90feac165\">" +
				"<CreationDate>2011-05-20T14:12:31.323Z</CreationDate>" +
				"<ProductId>c856c318-51e1-468a-b950-8bc3ed3e5b89</ProductId>" +
				"<CustomerId>4857230038</CustomerId>" +
			"</ReferencedEntitlement>" +
			"<ReferencedEntitlement id=\"4504a142-d39c-4af4-8314-62b90feac165\">" +
				"<CreationDate>2011-05-20T14:12:31.323Z</CreationDate>" +
				"<ProductId>c856c318-51e1-468a-b950-8bc3ed3e5b8x</ProductId>" +
				"<CustomerId>485723003x</CustomerId>" +
				"</ReferencedEntitlement>" +
			"</root>";
			

	Document doc = DocumentHelper.parseText(xml);

	for (Element noh : ((List<Element>)doc.selectNodes("//ReferencedEntitlement/CustomerId"))) {
		String texto = noh.getTextTrim();
		System.out.println("Vendo: " + noh.asXML() + "(" + texto + ")");
		if (texto != null && texto.endsWith("0038")) {
			//remove o referenced...
			System.out.println("Removendo " + noh.getParent().asXML());
			noh.getParent().detach();
		}
	}
	
	//o que sobrou:
	System.out.println(doc.asXML());
}

}[/code]

olha como estou fazendo

public class Main {
	String caminho = "C:" + File.separator + "Desenvolvimento" + File.separator
			+ "XML" + File.separator + "VODUsage_007099_20110520151501.xml";
	String caminhoModificado = "C:" + File.separator + "Desenvolvimento"
			+ File.separator + "XML" + File.separator
			+ "VODUsage_007099_20110520151501MOD.xml";

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		try {
			new Main().converter();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private String retornaValor(Element elem, String tagName) throws Exception {
		NodeList children = elem.getElementsByTagName(tagName);
		if (children == null)
			return null;
		Element child = (Element) children.item(0);
		if (child == null)
			return null;
		return child.getFirstChild().getNodeValue();
	}

	private boolean validarNumero(String numero) {
		Pattern p = Pattern.compile("[0-9]*0038");
		Matcher m = p.matcher(numero);
		return m.matches();

	}

	public void converter() throws Exception {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = db.parse(caminho);
		Element raiz = doc.getDocumentElement();
		NodeList listaReference = raiz
				.getElementsByTagName("ReferencedEntitlement");
		int tamanho = listaReference.getLength();

		for (int i = 0; i < tamanho; i++) {
			Element elemento = (Element) listaReference.item(i);
			NodeList n = elemento.getChildNodes();
			for (int x = 0; x < n.getLength(); x++) {
				if (n.item(x).getNodeName().equals("CustomerId")) {
					String numero = retornaValor(elemento, "CustomerId");
					if (validarNumero(numero)) {
						raiz.removeChild(elemento);
					}
				}
			}
		}

		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(new FileOutputStream(new File(
				caminhoModificado)));
		TransformerFactory transFactory = TransformerFactory.newInstance();
		Transformer transformer = transFactory.newTransformer();
		transformer.transform(source, result);

	}

}

mais na hora de remover “raiz.removeChild(elemento);”

ele gera a seguinte exceção

org.w3c.dom.DOMException: NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist.
	at com.sun.org.apache.xerces.internal.dom.ParentNode.internalRemoveChild(ParentNode.java:497)
	at com.sun.org.apache.xerces.internal.dom.ParentNode.removeChild(ParentNode.java:478)
	at Main.converter(Main.java:77)
	at Main.main(Main.java:37)

Eu não conheço o DOM/XML “padrão” do Java, desculpe. Acho que não poderei te ajudar.

Porém recomendo que você troque para o Dom4J (+ Jaxen, que é a dependência para o XPath funcionar) se possível :slight_smile:

Deixa eu justificar: a biblioteca é bem documentada, vem com vários “selectNodes” que funcionam com XPath. Tem também conversão fácil para e dê Strings. E é uma lib que vem por “padrão” no JBoss, o que facilita o uso quando em servidor de aplicativo.

cara não consegui usar seu exemplo ele pede pra fazer um monte de cast

eu tenho que add bibliotecas? eu não conheço este, ja aproveitando vc fala //remove o referenced… como eu removo?

Isso no Java 6?

Se você quiser, eu posso tentar colocar o projeto Eclipse zipado aqui…

pode ser java 6,seria muito bom srs

Sim! Dom4j 1.6.1 e Jaxen 1.1.3.

se possivel, não for pedir muito, me manda o projeto zipado, ja vem com as bibliotecas ne?

dom4j-2.0.0-ALPHA-2 2010-04-05 15.672 downloads
dom4j 2.0 ALPHA 2010-01-25 2.735 downloads
dom4j

qual eu baixo?

Vamos ver se o fórum aceita…

Tá lá.

Muito obrigado por estar me ajudando,

o como eu removo a referencia

//remove o referenced…?

É a linha de baixo…

noh.getParent().detach();  //isso remove a referência!

então aqui ele recebe

mais no meu caso ele precisa receber um file tem alguma forma

Document doc = DocumentHelper.parseText(FILE);

^^

O Guia é seu amigo…

[quote]Parsing XML

One of the first things you’ll probably want to do is to parse an XML document of some kind. This is easy to do in dom4j. The following code demonstrates how to this.[/quote]

[code]import java.net.URL;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

public class Foo {

public Document parse(URL url) throws DocumentException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(url);
    return document;
}

}[/code]

Só fazer o read com o File…

Ou usar o CommonsIO para ler tudo pra String…

Document doc = DocumentHelper.parseText(FileUtils.readFileToString(file)); 

fiz assim

public void converter() throws Exception {
		SAXReader reader = new SAXReader();
		File arquivo = new File(caminho);
		Document doc = reader.read(arquivo);
        
        for (Element noh : ((List<Element>)doc.selectNodes("//ReferencedEntitlement/CustomerId"))) {  
            String texto = noh.getTextTrim();  
            System.out.println("Vendo: " + noh.asXML() + "(" + texto + ")");  
            if (texto != null && texto.endsWith("038")) {  
                //remove o referenced...  
                System.out.println("Removendo " + noh.getParent().asXML());  
                noh.getParent().detach();  
            }  
        }  
          
	}

mais ele não entra no for , JA APROVEITANDO o 038 temque ser os ultimos caracteres da seguencia

estrutura do xml esta assim


 <References>
    <ReferencedEntitlements>
      <ReferencedEntitlement id="sfsdfsdfa5">
        <CreationDate>dfsfsdf</CreationDate>
        <ProductId>sdfsdfsd</ProductId>
        <CustomerId>545645645213038</CustomerId>
      </ReferencedEntitlement>

     <ReferencedEntitlement id="5eb81fd1-985a-4a18-85c1-fc8c0c4dd989">
        <CreationDate>645645654</CreationDate>
        <ProductId>5456566</ProductId>
      </ReferencedEntitlement>

</ReferencedEntitlements>
    <ReferencedAssets>
      <ReferencedAsset id="4645645645">
        <ExternalId>45648245</ExternalId>
        <Titles>
          <Title lang>456od</Title>
        </Titles>
        <IngestSource></IngestSource>
        <ContentProviderId>dlatv.net</ContentProviderId>
        <BillingId>04561</BillingId>
        <ContractName>Robin 464565497</ContractName>
      </ReferencedAsset>
  </References>
</VodUsage>

eu tentei fazer assim root.elementIterator( “//VodUsage/References/ReferencedEntitlements/ReferencedEntitlement/CustomerId”)

mais nada