我想解析具有相同父子标记的XML,然后使用SAX解析器将父标记的值链接到子标记。
这是XML文件
<?xml version="1.0" encoding="UTF-8"?>
<!-- Protocol header -->
<Protocol id="Diameter customer, country" spec="RFC3588"
name="Diameter" version="1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="file:/$CLASSES/cmg/stdapp/diameter/validation/Diameter_addon_schema.xsd">
<!-- ACR declaration: Start -->
<Request name="Start">
<Condition key="Accounting-Record-Type" value="2"/>
<AVP name="Node-Id" defaultValue="MTAS"/>
<AVP name="Session-Id"/>
<AVP name="Origin-Host"/>
<AVP name="Subscription-Id">
<AVP name="Subscription-Id-Type"/>
<AVP name="Subscription-Id-Data"/>
</AVP>
<AVP name="IMS-Information">
<AVP name="Event-Type">
<AVP name="SIP-Method"/>
</AVP>
<AVP name="Role-of-Node"/>
</AVP>
</Request>
<!---->
</Protocol>
在此示例中,名为AVP
的代码具有同名AVP
的子代码。我想获取属性名称的值,然后将parent的值与child的值相关联。我用
SAX解析器,但我无法区分父和子,但父和子标签没有区别。
Java代码
public void startElement(String s, String s1, String elementName, Attributes attributes) throws SAXException
{
if (elementName.equalsIgnoreCase("AVP"))
{
AVP_Tmp = new AVP();
String nameValue = attributes.getValue("name");
if (nameValue == null)
{
nameValue =attributes.getValue("value");
}
if (nameValue != null)
{
AVP_Tmp.set(nameValue,elementName,attributes);
}
}
}
@Override
public void endElement(String s, String s1, String element) throws SAXException
{
if (element.equals("AVP"))
{
Object key = AVP_Tmp.tmpValue;
Object value = AVP_Tmp.tmpValue;
AVPL.put(key, value);
}
}
AVP_Tmp
是一个类,其set方法如下:
public void set(String nameValue, String qName, Attributes attrs)//, int k)
{
int len = attrs.getLength();
tmpValue=qName + "-->" + nameValue;
List list = new ArrayList();
for (int i = 0; i < len; i++)
{
list.add(attrs.getQName(i));
}
Collections.sort(list);
for (int i = 0; i < len; i++)
{
name1[i]= (Object)list.get(i);
value1[i]=(attrs.getValue((String) list.get(i)));
tmpValue=tmpValue+ "\n" +name1[i]+"="+value1[i];
}
}
我目前输出为:
Node-Id
..
..
Subscription-Id
Subscription-Id-Type
IMS-Information
Event-Type
SIP-Method
..
我希望输出的格式如下:
Node-Id
..
..
..
Subscription-Id#Subscription-Id-Type
IMS-Information#Event-Type#SIP-Method
..
答案 0 :(得分:0)
当我实现你的目标时,我会这样做,你建立了&#34; AVP-Structure&#34;然后提取所需的输出。
因此,当新的AVP启动时,它看起来就像那样(只是伪代码):
if (parent == null){
avpTemp = new AVP();
parent = avpTemp;
} else {avpTemp = new AVP(parent); }
解析后,您已获得层次结构并根据需要构建结构/结果。