2013-04-16 2 views
0

그의 모든 자녀 읽어속성으로 태그를 찾아 나는이 xml 파일이

<?xml version="1.0" encoding="UTF-8"?> 
<Products> 
<Product productName="testProduct1"> 
    <Fields> 
     <Field name="Stack" /> 
     <Field name="Overflow" /> 
    </Fields> 
    <AnotherFields> 
     <Field name="Test" /> 
    </AnotherFields> 
</Product> 
<Product productName="testProduct"> 
    <Fields> 
     <Field name="StackOverflow" /> 
    </Fields> 
</Product> 
</Products> 

을 그리고 속성 productName의 독점적 인 가치를 가지고 product의 모든 자식 태그를 읽을 수에게, 다른 모든 태그는 생략 할 것입니다 .

public void mainParser(XmlResourceParser configXML, String productNameParameter) 
     throws XmlPullParserException, IOException { 
    int eventType = -1; 
    String strName, productName; 

    while (eventType != XmlResourceParser.END_DOCUMENT) { 
     if (eventType == XmlResourceParser.START_TAG) { 

      strName = configXML.getName(); 

      if (strName.equals("Product")) { 
       if (eventType == XmlResourceParser.START_TAG) { 

        productName = configXML.getAttributeValue(null, "productName"); 

        if (productName.equals(productNameParameter)) { 
         eventType = configXML.next(); 

         //here is the problem 

        } 
       } 
      } 
     } 
     eventType = configXML.next(); 
    } 
} 

누군가가 도와 드릴까요 :

그리고 여기에 내가 끼 었어 내 자바 코드?

답변

1

나는 단지 한 단계가 아니라 중첩 루프에서 이벤트 유형을 확인하고 특정 "제품"요소 안에있는 것을 나타내는 부울 플래그를 사용하는 것이 좋습니다 :

boolean foundIt = false; 
while (eventType != XmlResourceParser.END_DOCUMENT) { 
    strName = configXML.getName(); 

    if (eventType == XmlResourceParser.START_TAG) { 
     if (!foundIt && strName.equals("Product")) { 
      productName = configXML.getAttributeValue(null, "productName"); 

      if (productName.equals(productNameParameter)) { 
       foundIt = true; 
      } 
     } 
     else if (foundIt) { 
      // Children 
     } 
    } 
    else if (eventType == XmlResourceParser.END_TAG) { 
     if (foundIt && strName.equals("Product")) { 
      foundIt = false; 
      return; // You've found what you want, leave method 
     } 
    } 

    eventType = configXML.next(); 
} 

이제 configXML.next()를 호출하지 않습니다 또는 여러 곳에서 eventType을 확인하면 혼란 스러울 수 있습니다. foundIt이 true이면 "Product"태그를 찾지 않고 기본적으로 모든 새 요소를 읽는 것을 멈 춥니 다. 마지막으로 "제품"의 끝 태그를 읽으면 모든 것을 중단하십시오.