我使用SAXParser來讀取xml格式。然後運行startelement方法,但我不知道如何獲取方法中的url。我不知道解決方案是什麼。謝謝如何獲取SAX解析器中的屬性值
<enclosure length="1234567" type="image/jpeg" url="http://www.nasa.gov/images/content/664322main_31_lands_cropped_516-387.jpg"/>
我使用SAXParser來讀取xml格式。然後運行startelement方法,但我不知道如何獲取方法中的url。我不知道解決方案是什麼。謝謝如何獲取SAX解析器中的屬性值
<enclosure length="1234567" type="image/jpeg" url="http://www.nasa.gov/images/content/664322main_31_lands_cropped_516-387.jpg"/>
的屬性將被傳入的startElement方法:
for (int i = 0; i < attrs.getLength(); i++) {
String attributeName = attrs.getLocalName(i);
String attributeValue = attrs.getValue(i);
System.out.println("found attribute with localname=" + attributeName
+ " and value=" + attributeValue");
}
什麼語言?什麼實施?它始終是一個好主意,至少標籤的語言,你正在試圖實現
的想法是通過在的startElement()函數/方法的屬性參數進行迭代:
一個Java的解決方案:
public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
{
int len = atts.getLength();
// Loop through all attributes and save them as needed
for(int i = 0; i < len; i++)
{
String sAttrName = atts.getLocalName(i);
if(sAttrName.compareTo("URL") == 0)
{
String sVal = atts.getValue(i);
// Do something with the *.jpg
}
}
}
A C++ Xercesc解決方案:
void MyClass::startElement(const XMLCh *const uri, const XMLCh *const localname,
const XMLCh *const qname, const Attributes &attributes)
{
// Loop through all attributes and save them as needed
XMLSize_t len = attributes.getLength();
for(XMLSize_t index = 0; index < len; index++)
{
CString cAttrName(attributes.getLocalName(index));
if(cAttrName.Compare(L"URL") == 0)
{
CString cVal(attributes.getValue(index));
// Do something with the *.jpg
}
}
}
這裏是我在SAX ContentHandler嘗試;它返回屬性和鍵/值對。
private String mCurrentEl = null;
/** on each element: start */
public void startElement (String uri, String localName, String qName, Attributes attrs) throws SAXException {
/** keeping a reference */
mCurrentEl = localName;
/** each attribute */
for (int i=0; i < attrs.getLength(); i++) {
String name = attrs.getLocalName(i);
String value = attrs.getValue(i);
System.out.println("attribute \"" + name + "\" has value \"" + value + "\".");
}
}
/** on each element: data */
public void characters(char[] chars, int start, int length) throws SAXException {
String data = new String(chars, start, length).trim();
if(! data.equals("") && mCurrentEl != null) {
System.out.println(mCurrentEl + ": " + data);
}
}
/** on each element: end */
public void endElement(String uri, String localName, String qName) throws SAXException {
mCurrentEl = null;
}