java - xml文件操作

标签 java

我需要为包含内容的标签生成一个 ID。我正在使用 STAX 来读取 XML。我已阅读该文件并获取了包含内容的标签,但我无法正确生成它们的 ID。下面我贴出了java代码。

xml:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="TuneTestgram.xsl"?>
<root>
    <titlegroup>
        <titlelabel id="desc1">Unit 1</titlelabel>
        <maintitle id="desc2"></maintitle>
        <hr/>
    </titlegroup>
    <header>
        <div>  
            <title id="desc3">Main points dad</title>
            <P id="desc4">svn<br/></P>
            <P id="desc5">This is a book published by harper collins on 
                          <em><u>XML .</u></em><br/><br/>This is a book that has<br/>
            </P>
            <P id="desc6">Clauses can also have another noun group as the object or 
                          complement. test<br/>line1<br/>line1.1<br/>line1.2<br/>
                          line2<br/>line3<br/><br/><br/>
            </P>
            <P id="desc7">Clauses can <span style="text-decoration: underline;">
                          have</span> an adverbial, 
                          <sup><span style="font-style: italic;">also</span></sup> 
                          called <sub>an</sub> adjunct.
                          <span style="font-weight: bold;">ram</span>
            </P>
            <P id="desc8">Changing <br/></P>
            <P id="desc9">Compound sentences consist of two or more main clauses. 
                          Complex sentences always include a subordinate clause, 
                          as well as one or more main clauses.dad dad dgah test
            </P>
        </div>
    </header>
    <list>
        <label id="desc10">1</label>
        <li id="desc11">A simple sentence has one clause, beginning with a noun group 
                        called the subject. The subject is the person or thing that 
                        the sentence is about. This is followed by a verb group, which 
                        tells you what the subject is doing, or describes the 
                        subject's situation.dad adhagf hfhgfhgf das
        </li>
    </list>
    <P id="desc12"><i>Iwaited.<strong>dad</strong></i></P> 
    <P id="desc13"><i>Thegirlscreamed.</i><strong>dad</strong></P>
</root>
<小时/>
package pack;

import java.io.FileReader;
import java.io.FileWriter;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;

public class testingstax 
{

    public static void main(String args[])throws Exception
    {
        FileReader input= new FileReader("E:\\Java\\teststax\\src\\pack\\TuneTest.xml");
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader r = factory.createXMLStreamReader(input);
        FileWriter fw=new FileWriter("E:\\Java\\teststax\\src\\pack\\TuneTest2.xml");
        XMLOutputFactory output = XMLOutputFactory.newInstance();
        XMLStreamWriter writer = output.createXMLStreamWriter(fw );
        String s3;
        int i,n,j=0;
        try 
        {
            int event = r.getEventType()
            while (true) 
            {
                switch (event) 
                {
                    case XMLStreamConstants.START_DOCUMENT:
                        System.out.println("Start Document.");
                        break;
                    case XMLStreamConstants.START_ELEMENT:
                        System.out.println("Start Element: " + r.getName());
                        String s=r.getName().toString();
                        writer.writeStartElement(s);

                        for( i = 0, n = r.getAttributeCount(); i < n; ++i)
                            writer.writeAttribute(r.getAttributeName(i).toString(),
                                                  r.getAttributevalue(i));
                        break;
                    case XMLStreamConstants.CHARACTERS:
                        if (r.isWhiteSpace())
                            break;   
                        System.out.println("Text: " + r.getText());
                        writer.writeAttribute("ids",String.valueOf(++j));
                        writer.writeCharacters(r.getText());
                        break;
                    case XMLStreamConstants.END_ELEMENT:
                        System.out.println("End Element:" + r.getName());
                        writer.writeEndElement();
                        break;
                    case XMLStreamConstants.END_DOCUMENT:
                        System.out.println("End Document.");
                        break;
                }

                if (!r.hasNext())
                    break;
                event = r.next();
                // writer.writeCharacters("\n");
            }
        } finally 
        {
            writer.flush();
            writer.close();
            r.close();
        }
    }
}

异常(exception):

Exception in thread "main" javax.xml.stream.XMLStreamException: Attribute not associated with any element
    at com.sun.xml.internal.stream.writers.XMLStreamWriterImpl.writeAttribute(Unknown Source)
    at pack.testingstax.main(testingstax.java:55)

最佳答案

case XMLStreamConstants.CHARACTERS 可能会在标记内出现多次。第二次就不能写属性了。我认为这就是错误。

所以你需要一个状态:

boolean firstChars = false;

...

case XMLStreamConstants.START_ELEMENT:
    firstChars = true;

case XMLStreamConstants.CHARACTERS:
    if (firstChars) {
        firstChars = false;
        writer.writeAttribute...

关于java - xml文件操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9462540/

相关文章:

java - 关于 Java 到 XML 转换的问题,反之亦然

java - 在进入循环之前显示 GlassPane

java - 将一些获取和设置代码从 C# 转换为 Java

java - 使用 Spring-Data Elasticsearch 在 Elasticsearch 中动态创建索引名称

java - 我如何从这个 jogl 程序中获得每秒更多的帧数?

java - Tomcat 不会从 HTTP 重定向到 HTTPS

java - 在 ListView 中过滤数据

java - 别名不起作用

java - 如何管理用户身份验证/ session ?

java - 如何从 Servlet 2.3 或 2.5 中的响应中获取 header