草庐IT

android - 写xml有困难

coder 2024-07-02 原文

我试图使用 xmlSerializer 制作一个 xml 文件。这将从用户界面、用户名和密码中获取 2 个值。因此,每个条目都将附加到 xml 文件中。 如果我使用下面的代码,它只会保留最后一个条目-

FileOutputStream fileos= getApplicationContext().openFileOutput(xmlFile, Context.MODE_PRIVATE);

同样,如果我使用 MODE_APPEND 而不是 private,那么它会获取所有给定的 xml 标记 -like version 等等。

FileOutputStream fileos= getApplicationContext().openFileOutput(xmlFile, Context.MODE_APPEND);

但我只需要附加条目 - 这是 xml 文件中的用户名和密码标签。

下面是我的全部代码:

public class MainActivity extends Activity 
{

EditText txtKey;
EditText txtValue;
Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txtKey = (EditText)findViewById(R.id.txtvwKey);
    txtValue = (EditText)findViewById(R.id.txtvwValue);
    btn = (Button)findViewById(R.id.btnSave);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}




public void saveClk(View v) 
throws FileNotFoundException, SAXException
{
    final String xmlFile="userMemo.xml";
    String key= txtKey.getText().toString();
    String val= txtValue.getText().toString();

    try {
    FileOutputStream fileos= getApplicationContext().openFileOutput(xmlFile, Context.MODE_APPEND);

    XmlSerializer xmlSerializer = Xml.newSerializer();              
    StringWriter writer = new StringWriter();
    xmlSerializer.setOutput(writer);
    xmlSerializer.startDocument("UTF-8",true);
    xmlSerializer.startTag(null, "userData");
        xmlSerializer.startTag(null, "userName");
            xmlSerializer.text(key);
        xmlSerializer.endTag(null,"userName");
        xmlSerializer.startTag(null,"password");
            xmlSerializer.text(val);
        xmlSerializer.endTag(null, "password");             
    xmlSerializer.endTag(null, "userData");
    xmlSerializer.endDocument();
    xmlSerializer.flush();
    String dataWrite=writer.toString();
    fileos.write(dataWrite.getBytes());
    fileos.close();
    } 


    catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IllegalArgumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IllegalStateException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

 }
}

我该如何解决?

最佳答案

您使用的是 xerces-j 吗? 除非它是一个非常大(比如几百个 Mo)的 xml 文件,否则我建议您使用 DOM 而不是 SAX,更具可读性。

它看起来像:

public void saveClk(View v) throws FileNotFoundException, SAXException {
    final String xmlFile="userMemo.xml";
    // the name I suppose
    String key= txtKey.getText().toString();
    // the password I suppose
    String val= txtValue.getText().toString();

    // Load the xml from the file
    DOMParser parser = new DOMParser();
    parser.parse(xmlFile);
    Document doc = parser.getDocument();

    // Create a userData node: <userData></userData>
    Node userDataNode = dom.createElement("userData");

    // Create a username node: <userName></userName>
    Node userNameNode = dom.createElement("userName");
    // Add the userName node a  value as a child text node
    // -> <userName>username</userName>
    Text nodeVal = dom.createTextNode(key);
    userNameNode.appendChild(nodeVal);

    // Create a password node: <password></password>
    Node passwordNode = dom.createElement("password");
    // Add the userName node a  value as a child text node
    // -> <password>password</password>
    nodeVal = dom.createTextNode(value);
    passwordNode.appendChild(nodeVal);

    // -> <userData><userName>username</userName><password>password</password></userData>
    userDataNode.appendChild(userNameNode);
    userDataNode.appendChild(passwordNode);

    // Get the document's root XML node
    NodeList root = doc.getChildNodes();
    // append the newly created node as a new child (so keeping the existing data)
    root.appendChild(userDataNode);

    // Write updated XML
    doc = parser.getDocument();
    OutputFormat format = new OutputFormat(doc);
    format.setIndenting(true);
    XMLSerializer serializer = new XMLSerializer(new FileOutputStream(new File("userMemo.xml")), format);
    serializer.serialize(doc);
}

您尝试的问题是 MODE_APPEND 与文件编写器有关,而不是与 xml 序列化器有关。

关于android - 写xml有困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22191390/

有关android - 写xml有困难的更多相关文章

  1. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  2. 安卓apk修改(Android反编译apk) - 2

    最近因为项目需要,需要将Android手机系统自带的某个系统软件反编译并更改里面某个资源,并重新打包,签名生成新的自定义的apk,下面我来介绍一下我的实现过程。APK修改,分为以下几步:反编译解包,修改,重打包,修改签名等步骤。安卓apk修改准备工作1.系统配置好JavaJDK环境变量2.需要root权限的手机(针对系统自带apk,其他软件免root)3.Auto-Sign签名工具4.apktool工具安卓apk修改开始反编译本文拿Android系统里面的Settings.apk做demo,具体如何将apk获取出来在此就不过多介绍了,直接进入主题:按键win+R输入cmd,打开命令窗口,并将路

  3. ruby-on-rails - 如何在 Rails 3 中禁用 XML 解析 - 2

    我想禁用HTTP参数的自动XML解析。但我发现命令仅适用于Rails2.x,它们都不适用于3.0:config.action_controller.param_parsers.deleteMime::XML(application.rb)ActionController::Base.param_parsers.deleteMime::XMLRails3.0中的等价物是什么? 最佳答案 根据CVE-2013-0156的最新安全公告你可以将它用于Rails3.0。3.1和3.2ActionDispatch::ParamsParser::

  4. ruby - 如何使用 Nokogiri::XML::Builder 生成动态标签? - 2

    我正在遍历数组中的一组标签名称,我想使用构建器打印每个标签名称,而不是求助于“我认为:builder=Nokogiri::XML::Builder.newdo|xml|fortagintagsxml.tag!tag,somevalendend会这样做,但它只是创建名称为“tag”的标签,并将标签变量作为元素的文本值。有人可以帮忙吗?这个看起来应该比较简单,我刚刚在搜索引擎上找不到答案。我可能没有以正确的方式提问。 最佳答案 尝试以下操作。如果我没记错的话,我添加了一个根节点,因为Nokogiri需要一个。builder=Nokogi

  5. ruby - 如何让 Nokogiri 解析并返回 XML 文档? - 2

    这是一些奇怪的例子:#!/usr/bin/rubyrequire'rubygems'require'open-uri'require'nokogiri'print"withoutread:",Nokogiri(open('http://weblog.rubyonrails.org/')).class,"\n"print"withread:",Nokogiri(open('http://weblog.rubyonrails.org/').read).class,"\n"运行此返回:withoutread:Nokogiri::XML::Documentwithread:Nokogiri::

  6. ruby - 模式加载时出现 Nokogiri::XML::Schema SyntaxError - 2

    我正在尝试加载SAML协议(protocol)架构(具体来说:https://www.oasis-open.org/committees/download.php/3407/oasis-sstc-saml-schema-protocol-1.1.xsd),但在执行此操作之后:schema=Nokogiri::XML::Schema(File.read('saml11_schema.xsd'))我得到这个输出:Nokogiri::XML::SyntaxErrorException:Element'{http://www.w3.org/2001/XMLSchema}element',att

  7. ruby-on-rails - 来自 cucumber 的 HTTP POST XML 内容 - 2

    我正在尝试通过POST将XML内容发送到一个简单的Rails项目中的Controller(“解析”)方法(“索引”)。它不是RESTful,因为我的模型名称不同,比如“汽车”。我在有效的功能测试中有以下内容:deftest_index...data_file_path=File.dirname(__FILE__)+'/../../app/views/layouts/index.xml.erb'message=ERB.new(File.read(data_file_path))xml_result=message.result(binding)doc=REXML::Document.ne

  8. Android Studio开发之使用内容组件Content获取通讯信息讲解及实战(附源码 包括添加手机联系人和发短信) - 2

    运行有问题或需要源码请点赞关注收藏后评论区留言一、利用ContentResolver读写联系人在实际开发中,普通App很少会开放数据接口给其他应用访问。内容组件能够派上用场的情况往往是App想要访问系统应用的通讯数据,比如查看联系人,短信,通话记录等等,以及对这些通讯数据及逆行增删改查。首先要给AndroidMaifest.xml中添加响应的权限配置 下面是往手机通讯录添加联系人信息的例子效果如下分成三个步骤先查出联系人的基本信息,然后查询联系人号码,再查询联系人邮箱代码 ContactAddActivity类packagecom.example.chapter07;importandroid

  9. Android 10.0 设置默认launcher后安装另外launcher后默认Launcher失效的功能修复 - 2

    1.前言 在10.0的系统rom定制化开发中,在系统中有多个launcher的时候,会在开机进入launcher的时候弹窗launcher列表,让用户选择进入哪个launcher,这样显得特别的不方便所以产品开发中,要求用RoleManager的相关api来设置默认Launcher,但是在设置完默认Launcher以后,在安装一款Launcher的时候,默认Launcher就会失效,在系统设置的默认应用中Launcher选项就为空,点击home键的时候会弹出默认Launcher列表,让选择进入哪个默认Launcher.所以需要从安装Launcher的流程来分析相关的设置。来解决问题设置默认La

  10. ruby - 如何使用 XPath 和 Nokogiri 获取 XML 节点的内容 - 2

    我有这样的代码:@doc=Nokogiri::HTML(open(url)@doc.xpath(query).eachdo|html|putshtml#howgetcontentofanodeend我如何获取节点的内容而不是像这样: 最佳答案 这是READMEfile中的概要示例为Nokogiri展示了一种使用CSS、XPath或混合的方法:require'nokogiri'require'open-uri'#GetaNokogiri::HTML:Documentforthepagewe’reinterestedin...doc=N

随机推荐