读 XML 文件和 写 XML 文件- 通过JAXB 实现

这篇博客详细介绍了如何通过JAXB实现XML文件的读取和写入。首先,展示了生成对应XSD文件的过程,然后使用xjc命令将XSD转换为Java对象。接着,演示了XML到Java对象的转换,并提供了关键代码示例。最后,讨论了写入XML文件时可能出现的问题,如额外的standalone属性和命名空间顺序,并分享了完整的源代码链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

读 XML 文件

测试文件

test.xml

<?xml version="1.0" encoding="UTF-8" ?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:mobile="http://www.baidu.com/schemas/sitemap-mobile/1/">
    <url>
        <loc>http://m.example.com/index.html</loc>
        <mobile:mobile type="mobile"/>
        <lastmod>2009-12-14</lastmod>
        <changefreq>daily</changefreq>
        <priority>0.8</priority>
    </url>
    <url>
        <loc>http://www.example.com/index.html</loc>
        <lastmod>2009-12-14</lastmod>
        <changefreq>daily</changefreq>
        <priority>0.8</priority>
    </url>
    <url>
        <loc>http://www.example.com/autoadapt.html</loc>
        <mobile:mobile type="pc,mobile"/>
        <lastmod>2009-12-14</lastmod>
        <changefreq>daily</changefreq>
        <priority>0.8</priority>
    </url>
    <url>
        <loc>http://www.example.com/htmladapt.html</loc>
        <mobile:mobile type="htmladapt"/>
        <lastmod>2009-12-14</lastmod>
        <changefreq>daily</changefreq>
        <priority>0.8</priority>
    </url>
</urlset>

生成对应的 xsd 文件

xsd 文件内容

test.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:mobile="http://www.baidu.com/schemas/sitemap-mobile/1/" xmlns:sitemap="http://www.sitemaps.org/schemas/sitemap/0.9">
  <xs:import namespace="http://www.baidu.com/schemas/sitemap-mobile/1/" schemaLocation="mobile.xsd"/>
  <xs:element name="urlset">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值