【问题标题】:Set Attribute Value设置属性值
【发布时间】:2023-03-22 19:15:01
【问题描述】:

如何在创建 xml 文件期间为 id 属性设置值,其中 id 值可以是任何值,例如它可以是 id="1" 或 id="A" 或 id="k1",id= “k2”

public void process(String s) throws SAXException {

    try {

        atts.clear();
        k++;
        atts.addAttribute("", "", "id", "", "" + k);
        th.startElement("", "", "trans-unit", atts);
        th.startElement("", "", "target", null);
        th.characters(elements[i].toCharArray(), 0, elements[i].length());
        th.endElement("", "", "target");
        th.endElement("", "", "trans-unit");

     }

【问题讨论】:

    标签: java xml sax


    【解决方案1】:

    我假设您从this question 复制了代码,该代码适用于 OP,因此您的问题一定出在其他地方。请提供有关失败原因的更多信息。

    另外,看看这个easier implementation,也许对你有帮助。

    编辑

    你只需要改变addAttribute的最后一个参数

    atts.addAttribute("", "", "id", "", yourStringOfChoiceHere);
    

    addArttibute 的文档是 here。如果您打算在代码中保留 process 方法,您可能希望将 id 值添加为变量

    public void process(String s, String idValue) throws SAXException {
    
    ...
        atts.addAttribute("", "", "id", "", idValue);
    ...
    
    }
    

    【讨论】:

    • 感谢您的回答,我想知道是否可以为“id”设置不仅增加的数字,还设置其他属性值,如果可以,怎么做?
    • 类似,这些值“A-Z”或“i1-i9”
    • 例如atts.addAttribute("", "", "id", "", "anything_here");。 addArttibute 的文档是 here(添加到主要答案中)
    猜你喜欢
    • 2011-10-11
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 2022-09-23
    • 2011-10-14
    • 1970-01-01
    相关资源
    最近更新 更多