java JAXB STAX & net core XmlReader.Create(stream ) 流的方式读取xml文件。

JAVA对XML文件操作细节处理

JAXB命名空间及命名空间前缀处理

java对xml文件的操作

复制代码
   1 package tb.helper;
   2 
   3 import java.io.BufferedOutputStream;
   4 import java.io.File;
   5 import java.io.FileInputStream;
   6 import java.io.FileNotFoundException;
   7 import java.io.FileOutputStream;
   8 import java.io.FileReader;
   9 import java.io.IOException;
  10 import java.io.InputStreamReader;
  11 import java.io.OutputStream;
  12 import java.io.OutputStreamWriter;
  13 import java.io.PrintStream;
  14 import java.io.PrintWriter;
  15 import java.io.Reader;
  16 import java.io.StringReader;
  17 import java.io.StringWriter;
  18 import java.io.UnsupportedEncodingException;
  19 import java.io.Writer;
  20 import java.util.ArrayList;
  21 import java.util.List;
  22 import java.util.zip.GZIPInputStream;
  23 
  24 import javax.xml.bind.JAXBContext;
  25 import javax.xml.bind.JAXBElement;
  26 import javax.xml.bind.JAXBException;
  27 import javax.xml.bind.Marshaller;
  28 import javax.xml.bind.Unmarshaller;
  29 import javax.xml.namespace.QName;
  30 import javax.xml.stream.EventFilter;
  31 import javax.xml.stream.StreamFilter;
  32 import javax.xml.stream.XMLEventReader;
  33 import javax.xml.stream.XMLInputFactory;
  34 import javax.xml.stream.XMLOutputFactory;
  35 import javax.xml.stream.XMLStreamException;
  36 import javax.xml.stream.XMLStreamReader;
  37 import javax.xml.stream.XMLStreamWriter;
  38 import javax.xml.stream.events.StartElement;
  39 import javax.xml.stream.events.XMLEvent;
  40 import javax.xml.transform.OutputKeys;
  41 import javax.xml.transform.Transformer;
  42 import javax.xml.transform.TransformerException;
  43 import javax.xml.transform.TransformerFactory;
  44 import javax.xml.transform.stax.StAXResult;
  45 import javax.xml.transform.stax.StAXSource;
  46 
  47 import tb.csharp.delegate.Action1;
  48 import tb.csharp.delegate.Func1;
  49 import tb.helper.xml.CDataXMLStreamWriter;
  50 
  51 import javanet.staxutils.IndentingXMLStreamWriter;
  52 
  53 /**
  54  * 
  55  * JAXB:JAXB 的全名是Java ™ Architecture for XML Binding
  56  * 
  57  * STAX:StAX是Streaming API for XML的缩写,是一种针对XML的流式拉分析API。
  58  * 
  59  * @author wangyunpeng
  60  *
  61  */
  62 public class XmlHelper {
  63 
  64     /*
  65      * JAXB:JAXB 的全名是Java ™ Architecture for XML Binding
  66      * 
  67      * http://www.cnblogs.com/lzrabbit/p/3657854.html
  68      */
  69 
  70     /**
  71      * XML序列化对象,返回值是XML字符串
  72      * 
  73      * @param object
  74      *            要序列化的类加上 @XmlRootElement注解,否则会报错(错误提示很清晰,这里就不贴出来了)
  75      * @return
  76      * @throws JAXBException
  77      * @throws IOException
  78      */
  79     public static String serialize(Object object) throws JAXBException, IOException {
  80         JAXBContext context = JAXBContext.newInstance(object.getClass());
  81         return serialize(context, object);
  82     }
  83 
  84     /**
  85      * XML序列化对象,返回值是XML字符串
  86      * 
  87      * @param context
  88      * @param object
  89      * @return
  90      * @throws JAXBException
  91      * @throws IOException
  92      * @since JDK 1.7.79
  93      */
  94     public static String serialize(JAXBContext context, Object object) throws JAXBException, IOException {
  95         String xml = null;
  96         Marshaller marshaller = context.createMarshaller();
  97         marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// //编码格式
  98         marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 是否格式化生成的xml串
  99         marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);// 是否省略xml头声明信息
 100         StringWriter stringWriter = new StringWriter();
 101         try {
 102             marshaller.marshal(object, stringWriter);
 103             xml = stringWriter.toString();
 104         } catch (JAXBException e) {
 105             throw e;
 106         } finally {
 107             IOHelper.close(stringWriter);
 108             stringWriter = null;
 109             marshaller = null;
 110             context = null;
 111         }
 112         return xml;
 113     }
 114 
 115     /**
 116      * XML序列化对象到指定的Writer
 117      * 
 118      * @param writer
 119      * @param object
 120      * @throws JAXBException
 121      * @throws IOException
 122      */
 123     public static void serialize(Writer writer, Object object) throws JAXBException, IOException {
 124         JAXBContext context = JAXBContext.newInstance(object.getClass());
 125         serialize(writer, context, object);
 126     }
 127 
 128     /**
 129      * XML序列化对象到指定的Writer
 130      * 
 131      * @param writer
 132      * @param context
 133      * @param object
 134      * @throws JAXBException
 135      * @throws IOException
 136      * @since JDK 1.7.79
 137      */
 138     public static void serialize(Writer writer, JAXBContext context, Object object) throws JAXBException, IOException {
 139         Marshaller marshaller = context.createMarshaller();
 140         marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// //编码格式
 141         marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 是否格式化生成的xml串
 142         marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);// 是否省略xml头声明信息
 143         marshaller.marshal(object, writer);
 144         marshaller = null;
 145         context = null;
 146     }
 147 
 148     /**
 149      * XML序列化对象到指定的输出流
 150      * 
 151      * @param outputStream
 152      * @param object
 153      * @throws JAXBException
 154      * @throws IOException
 155      */
 156     public static void serialize(OutputStream outputStream, Object object) throws JAXBException, IOException {
 157         JAXBContext context = JAXBContext.newInstance(object.getClass());
 158         serialize(outputStream, context, object);
 159     }
 160 
 161     /**
 162      * XML序列化对象到指定的输出流
 163      * 
 164      * @param outputStream
 165      * @param context
 166      * @param object
 167      * @throws JAXBException
 168      * @throws IOException
 169      * @since JDK 1.7.79
 170      */
 171     public static void serialize(OutputStream outputStream, JAXBContext context, Object object) throws JAXBException, IOException {
 172         Marshaller marshaller = context.createMarshaller();
 173         marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// //编码格式
 174         marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 是否格式化生成的xml串
 175         marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);// 是否省略xml头声明信息
 176         marshaller.marshal(object, outputStream);
 177         marshaller = null;
 178         context = null;
 179     }
 180 
 181     /**
 182      * XML序列化对象到指定的文件中
 183      * 
 184      * @param xmlFilePath
 185      * @param object
 186      * @throws JAXBException
 187      * @throws IOException
 188      */
 189     public static void serialize(String xmlFilePath, Object object) throws JAXBException, IOException {
 190         JAXBContext context = JAXBContext.newInstance(object.getClass());
 191         Marshaller marshaller = context.createMarshaller();
 192         marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// //编码格式
 193         marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 是否格式化生成的xml串
 194         marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);// 是否省略xml头声明信息
 195         File file = IOHelper.createFile(xmlFilePath);
 196         marshaller.marshal(object, file);
 197         file = null;
 198         marshaller = null;
 199         context = null;
 200     }
 201 
 202     /**
 203      * 将XML格式的字符串反序列化成对象
 204      * 
 205      * @param xmlString
 206      *            XML格式的字符串内容
 207      * @param cls
 208      * @return
 209      * @throws JAXBException
 210      */
 211     @SuppressWarnings("unchecked")
 212     public static <T> T deserialize(String xmlString, Class<T> cls) throws JAXBException {
 213         T object = null;
 214         JAXBContext context = JAXBContext.newInstance(cls);
 215         Unmarshaller unmarshaller = context.createUnmarshaller();
 216         StringReader stringReader = new StringReader(xmlString);
 217         try {
 218             object = (T) unmarshaller.unmarshal(stringReader);
 219         } catch (JAXBException e) {
 220             throw e;
 221         } finally {
 222             IOHelper.close(stringReader);
 223             stringReader = null;
 224             unmarshaller = null;
 225             context = null;
 226         }
 227         return object;
 228     }
 229 
 230     /**
 231      * 将XML格式的文件反序列化成对象
 232      * 
 233      * @param xmlFilePath
 234      * @param cls
 235      * @return
 236      * @throws JAXBException
 237      */
 238     @SuppressWarnings("unchecked")
 239     public static <T> T deserializeByFile(String xmlFilePath, Class<T> cls) throws JAXBException {
 240         T object = null;
 241         File file = new File(xmlFilePath);
 242         if (file.exists() && file.isFile()) {
 243             JAXBContext context = JAXBContext.newInstance(cls);
 244             Unmarshaller unmarshaller = context.createUnmarshaller();
 245             object = (T) unmarshaller.unmarshal(file);
 246             unmarshaller = null;
 247             context = null;
 248         }
 249         file = null;
 250         return object;
 251     }
 252 
 253     /*
 254      * STAX:StAX是Streaming API for XML的缩写,是一种针对XML的流式拉分析API。
 255      */
 256 
 257     /**
 258      * 获得Stream方式的XML解析器(指针读取器对象)
 259      * 
 260      * @param xmlFilePath
 261      *            XML文件路径 例如:String xmlFilePath = App.class.getResource("/").getFile() + "users.xml";
 262      * @return
 263      * @throws XMLStreamException
 264      * @throws IOException
 265      */
 266     public static XMLStreamReader getXmlStreamReader(String xmlFilePath) throws XMLStreamException, IOException {
 267         return getXmlStreamReader(xmlFilePath, "UTF-8");
 268     }
 269 
 270     /**
 271      * 获得Stream方式的XML解析器(指针读取器对象)
 272      * 
 273      * @param xmlFilePath
 274      *            XML文件路径 例如:String xmlFilePath = App.class.getResource("/").getFile() + "users.xml";
 275      * @param encoding
 276      *            XML文件的编码方式
 277      * @return
 278      * @throws XMLStreamException
 279      * @throws IOException
 280      */
 281     public static XMLStreamReader getXmlStreamReader(String xmlFilePath, String encoding) throws XMLStreamException, IOException {
 282         return getXmlStreamReader(new File(xmlFilePath), encoding);
 283     }
 284 
 285     /**
 286      * 获得Stream方式的XML解析器(指针读取器对象)
 287      * 
 288      * @param xmlFile
 289      *            XML文件
 290      * @return
 291      * @throws XMLStreamException
 292      * @throws IOException
 293      */
 294     public static XMLStreamReader getXmlStreamReader(File xmlFile) throws XMLStreamException, IOException {
 295         return getXmlStreamReader(xmlFile, "UTF-8");
 296     }
 297 
 298     /**
 299      * 获得Stream方式的XML解析器(指针读取器对象)
 300      * 
 301      * @param xmlFile
 302      *            XML文件
 303      * @param encoding
 304      *            XML文件的编码方式
 305      * @return
 306      * @throws XMLStreamException
 307      * @throws IOException
 308      */
 309     public static XMLStreamReader getXmlStreamReader(File xmlFile, String encoding) throws XMLStreamException, IOException {
 310         if (xmlFile.getName().endsWith(".gz")) {
 311             return getXmlStreamReader(new GZIPInputStream(new FileInputStream(xmlFile)), encoding);
 312         } else {
 313             return getXmlStreamReader(new FileInputStream(xmlFile), encoding);
 314         }
 315     }
 316 
 317     /**
 318      * 获得Event方式的XML解析器(事件读取器对象)
 319      * 
 320      * @param xmlGzipInputStream
 321      * @return
 322      * @throws FileNotFoundException
 323      * @throws XMLStreamException
 324      * @throws UnsupportedEncodingException
 325      */
 326     public static XMLStreamReader getXmlStreamReader(GZIPInputStream xmlGzipInputStream)
 327             throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
 328         return getXmlStreamReader(new InputStreamReader(xmlGzipInputStream, "UTF-8"));
 329     }
 330 
 331     /**
 332      * 获得Event方式的XML解析器(事件读取器对象)
 333      * 
 334      * @param xmlGzipInputStream
 335      * @param encoding
 336      * @return
 337      * @throws FileNotFoundException
 338      * @throws XMLStreamException
 339      * @throws UnsupportedEncodingException
 340      */
 341     public static XMLStreamReader getXmlStreamReader(GZIPInputStream xmlGzipInputStream, String encoding)
 342             throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
 343         return getXmlStreamReader(new InputStreamReader(xmlGzipInputStream, encoding));
 344     }
 345 
 346     /**
 347      * 获得Stream方式的XML解析器(指针读取器对象)
 348      * 
 349      * @param xmlFileInputStream
 350      * @return
 351      * @throws FileNotFoundException
 352      * @throws XMLStreamException
 353      * @throws UnsupportedEncodingException
 354      */
 355     public static XMLStreamReader getXmlStreamReader(FileInputStream xmlFileInputStream)
 356             throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
 357         return getXmlStreamReader(xmlFileInputStream, "UTF-8");
 358     }
 359 
 360     /**
 361      * 获得Stream方式的XML解析器(指针读取器对象)
 362      * 
 363      * @param xmlFileInputStream
 364      * @param encoding
 365      *            XML文件的编码方式
 366      * @return
 367      * @throws FileNotFoundException
 368      * @throws XMLStreamException
 369      * @throws UnsupportedEncodingException
 370      */
 371     public static XMLStreamReader getXmlStreamReader(FileInputStream xmlFileInputStream, String encoding)
 372             throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
 373         return getXmlStreamReader(new InputStreamReader(xmlFileInputStream, encoding));
 374     }
 375 
 376     /**
 377      * 获得Stream方式的XML解析器(指针读取器对象)
 378      * 
 379      * @param xmlInputStreamReader
 380      * @return
 381      * @throws FileNotFoundException
 382      * @throws XMLStreamException
 383      */
 384     public static XMLStreamReader getXmlStreamReader(InputStreamReader xmlInputStreamReader)
 385             throws FileNotFoundException, XMLStreamException {
 386         return getXmlStreamReader((Reader) xmlInputStreamReader);
 387     }
 388 
 389     /**
 390      * 获得Stream方式的XML解析器(指针读取器对象)
 391      * 
 392      * @param xmlFileReader
 393      * @return
 394      * @throws FileNotFoundException
 395      * @throws XMLStreamException
 396      */
 397     public static XMLStreamReader getXmlStreamReader(FileReader xmlFileReader) throws FileNotFoundException, XMLStreamException {
 398         return getXmlStreamReader((Reader) xmlFileReader);
 399     }
 400 
 401     /**
 402      * 获得Stream方式的XML解析器(指针读取器对象) 如果是XML字符串,建议使用JAXB方式直接得到java对象。 不建议使用STAX方式拉取数据,除非是XML字符串信息很大或者需要每一条每一条的读取XML字符串里面的元素进行针对性的操作,否则不建议使用。
 403      * 
 404      * @param xmlStringReader
 405      *            XML字符串,例如:String xml; StringReader stringReader = new StringReader(xml);
 406      * @return
 407      * @throws FileNotFoundException
 408      * @throws XMLStreamException
 409      */
 410     public static XMLStreamReader getXmlStreamReader(StringReader xmlStringReader)
 411             throws FileNotFoundException, XMLStreamException {
 412         return getXmlStreamReader((Reader) xmlStringReader);
 413     }
 414 
 415     /**
 416      * 获得Stream方式的XML解析器(指针读取器对象)
 417      * 
 418      * @param xmlReader
 419      * @return
 420      * @throws FileNotFoundException
 421      * @throws XMLStreamException
 422      */
 423     public static XMLStreamReader getXmlStreamReader(Reader xmlReader) throws FileNotFoundException, XMLStreamException {
 424         return XMLInputFactory.newInstance().createXMLStreamReader(xmlReader);
 425     }
 426 
 427     /**
 428      * 获得Stream方式的XML解析器(指针读取器对象),支持过滤器
 429      * 
 430      * @param xmlFilePath
 431      *            XML文件路径 例如:String xmlFilePath = App.class.getResource("/").getFile() + "users.xml";
 432      * @param streamFilter
 433      *            流式过滤器
 434      * @return
 435      * @throws FileNotFoundException
 436      * @throws XMLStreamException
 437      */
 438     public static XMLStreamReader getXmlStreamReader(String xmlFilePath, StreamFilter streamFilter)
 439             throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
 440         return getXmlStreamReader(xmlFilePath, "UTF-8", streamFilter);
 441     }
 442 
 443     /**
 444      * 获得Stream方式的XML解析器(指针读取器对象),支持过滤器
 445      * 
 446      * @param xmlFilePath
 447      *            XML文件路径 例如:String xmlFilePath = App.class.getResource("/").getFile() + "users.xml";
 448      * @param encoding
 449      *            XML文件的编码方式
 450      * @param streamFilter
 451      *            流式过滤器
 452      * @return
 453      * @throws FileNotFoundException
 454      * @throws XMLStreamException
 455      * @throws UnsupportedEncodingException
 456      */
 457     public static XMLStreamReader getXmlStreamReader(String xmlFilePath, String encoding, StreamFilter streamFilter)
 458             throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
 459         return getXmlStreamReader(new FileInputStream(xmlFilePath), encoding, streamFilter);
 460     }
 461 
 462     /**
 463      * 获得Stream方式的XML解析器(指针读取器对象),支持过滤器
 464      * 
 465      * @param xmlFile
 466      *            XML文件
 467      * @param streamFilter
 468      *            流式过滤器
 469      * @return
 470      * @throws FileNotFoundException
 471      * @throws XMLStreamException
 472      * @throws UnsupportedEncodingException
 473      */
 474     public static XMLStreamReader getXmlStreamReader(File xmlFile, StreamFilter streamFilter)
 475             throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
 476         return getXmlStreamReader(xmlFile, "UTF-8", streamFilter);
 477     }
 478 
 479     /**
 480      * 获得Stream方式的XML解析器(指针读取器对象),支持过滤器
 481      * 
 482      * @param xmlFile
 483      *            XML文件
 484      * @param encoding
 485      *            XML文件的编码方式
 486      * @param streamFilter
 487      *            流式过滤器
 488      * @return
 489      * @throws FileNotFoundException
 490      * @throws XMLStreamException
 491      * @throws UnsupportedEncodingException
 492      */
 493     public static XMLStreamReader getXmlStreamReader(File xmlFile, String encoding, StreamFilter streamFilter)
 494             throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
 495         return getXmlStreamReader(new FileInputStream(xmlFile), encoding, streamFilter);
 496     }
 497 
 498     /**
 499      * 获得Stream方式的XML解析器(指针读取器对象),支持过滤器
 500      * 
 501      * @param xmlFileInputStream
 502      *            XML文件流
 503      * @param streamFilter
 504      *            流式过滤器
 505      * @return
 506      * @throws FileNotFoundException
 507      * @throws XMLStreamException
 508      * @throws UnsupportedEncodingException
 509      */
 510     public static XMLStreamReader getXmlStreamReader(FileInputStream xmlFileInputStream, StreamFilter streamFilter)
 511             throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
 512         return getXmlStreamReader(xmlFileInputStream, "UTF-8", streamFilter);
 513     }
 514 
 515     /**
 516      * 获得Stream方式的XML解析器(指针读取器对象),支持过滤器
 517      * 
 518      * @param xmlFileInputStream
 519      *            XML文件流
 520      * @param encoding
 521      *            XML文件的编码方式
 522      * @param streamFilter
 523      *            流式过滤器
 524      * @return
 525      * @throws FileNotFoundException
 526      * @throws XMLStreamException
 527      * @throws UnsupportedEncodingException
 528      */
 529     public static XMLStreamReader getXmlStreamReader(FileInputStream xmlFileInputStream, String encoding,
 530             StreamFilter streamFilter) throws FileNotFoundException, XMLStreamException,
 531                     UnsupportedEncodingException {
 532         return getXmlStreamReader(new InputStreamReader(xmlFileInputStream, encoding), streamFilter);
 533     }
 534 
 535     /**
 536      * 获得Stream方式的XML解析器(指针读取器对象),支持过滤器
 537      * 
 538      * @param xmlInputStreamReader
 539      *            xml格式的输入流
 540      * @param streamFilter
 541      *            流式过滤器
 542      * @return
 543      * @throws FileNotFoundException
 544      * @throws XMLStreamException
 545      */
 546     public static XMLStreamReader getXmlStreamReader(InputStreamReader xmlInputStreamReader, StreamFilter streamFilter)
 547             throws FileNotFoundException, XMLStreamException {
 548         return getXmlStreamReader((Reader) xmlInputStreamReader, streamFilter);
 549     }
 550 
 551     /**
 552      * 获得Stream方式的XML解析器(指针读取器对象),支持过滤器
 553      * 
 554      * @param xmlFileReader
 555      *            xml文件读取器
 556      * @param streamFilter
 557      *            流式过滤器
 558      * @return
 559      * @throws FileNotFoundException
 560      * @throws XMLStreamException
 561      */
 562     public static XMLStreamReader getXmlStreamReader(FileReader xmlFileReader, StreamFilter streamFilter)
 563             throws FileNotFoundException, XMLStreamException {
 564         return getXmlStreamReader((Reader) xmlFileReader, streamFilter);
 565     }
 566 
 567     /**
 568      * 获得Stream方式的XML解析器(指针读取器对象),支持过滤器 如果是XML字符串,建议使用JAXB方式直接得到java对象。 不建议使用STAX方式拉取数据,除非是XML字符串信息很大或者需要每一条每一条的读取XML字符串里面的元素进行针对性的操作,否则不建议使用。
 569      * 
 570      * @param xmlStringReader
 571      * @param streamFilter
 572      * @return
 573      * @throws FileNotFoundException
 574      * @throws XMLStreamException
 575      */
 576     public static XMLStreamReader getXmlStreamReader(StringReader xmlStringReader, StreamFilter streamFilter)
 577             throws FileNotFoundException, XMLStreamException {
 578         return getXmlStreamReader((Reader) xmlStringReader, streamFilter);
 579     }
 580 
 581     /**
 582      * 获得Stream方式的XML解析器(指针读取器对象),支持过滤器
 583      * 
 584      * @param xmlReader
 585      *            xml格式的读取器
 586      * @param streamFilter
 587      *            流式过滤器
 588      * @return
 589      * @throws FileNotFoundException
 590      * @throws XMLStreamException
 591      */
 592     public static XMLStreamReader getXmlStreamReader(Reader xmlReader, StreamFilter streamFilter)
 593             throws FileNotFoundException, XMLStreamException {
 594         XMLStreamReader xmlStreamFilterReader = null;
 595         XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
 596         XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(xmlReader);
 597         xmlStreamFilterReader = xmlInputFactory.createFilteredReader(xmlStreamReader, streamFilter);
 598         return xmlStreamFilterReader;
 599     }
 600 
 601     /**
 602      * 释放Stream方式的XML解析器对象所占用的内存空间
 603      * 
 604      * @param xmlStreamReader
 605      * @throws XMLStreamException
 606      */
 607     public static void close(XMLStreamReader xmlStreamReader) throws XMLStreamException {
 608         if (xmlStreamReader != null) {
 609             xmlStreamReader.close();
 610             xmlStreamReader = null;
 611         }
 612     }
 613 
 614     /**
 615      * 获得Event方式的XML解析器(事件读取器对象)
 616      * 
 617      * @param xmlFilePath
 618      *            XML文件路径 例如:String xmlFilePath = App.class.getResource("/").getFile() + "users.xml";
 619      * @return
 620      * @throws XMLStreamException
 621      * @throws IOException
 622      */
 623     public static XMLEventReader getXmlEventReader(String xmlFilePath) throws XMLStreamException, IOException {
 624         return getXmlEventReader(xmlFilePath, "UTF-8");
 625     }
 626 
 627     /**
 628      * 获得Event方式的XML解析器(事件读取器对象)
 629      * 
 630      * @param xmlFilePath
 631      * @param encoding
 632      * @return
 633      * @throws XMLStreamException
 634      * @throws IOException
 635      */
 636     public static XMLEventReader getXmlEventReader(String xmlFilePath, String encoding) throws XMLStreamException, IOException {
 637         return getXmlEventReader(new File(xmlFilePath), encoding);
 638     }
 639 
 640     /**
 641      * 获得Event方式的XML解析器(事件读取器对象)
 642      * 
 643      * @param xmlFile
 644      * @return
 645      * @throws XMLStreamException
 646      * @throws IOException
 647      */
 648     public static XMLEventReader getXmlEventReader(File xmlFile) throws XMLStreamException, IOException {
 649         return getXmlEventReader(xmlFile, "UTF-8");
 650     }
 651 
 652     /**
 653      * 获得Event方式的XML解析器(事件读取器对象)
 654      * 
 655      * @param xmlFile
 656      * @param encoding
 657      * @return
 658      * @throws XMLStreamException
 659      * @throws IOException
 660      */
 661     public static XMLEventReader getXmlEventReader(File xmlFile, String encoding) throws XMLStreamException, IOException {
 662         if (xmlFile.getName().endsWith(".gz")) {
 663             return getXmlEventReader(new GZIPInputStream(new FileInputStream(xmlFile)), encoding);
 664         } else {
 665             return getXmlEventReader(new FileInputStream(xmlFile), encoding);
 666         }
 667     }
 668 
 669     /**
 670      * 获得Event方式的XML解析器(事件读取器对象)
 671      * 
 672      * @param xmlGzipInputStream
 673      * @return
 674      * @throws FileNotFoundException
 675      * @throws XMLStreamException
 676      * @throws UnsupportedEncodingException
 677      */
 678     public static XMLEventReader getXmlEventReader(GZIPInputStream xmlGzipInputStream)
 679             throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
 680         return getXmlEventReader(new InputStreamReader(xmlGzipInputStream, "UTF-8"));
 681     }
 682 
 683     /**
 684      * 获得Event方式的XML解析器(事件读取器对象)
 685      * 
 686      * @param xmlGzipInputStream
 687      * @param encoding
 688      * @return
 689      * @throws FileNotFoundException
 690      * @throws XMLStreamException
 691      * @throws UnsupportedEncodingException
 692      */
 693     public static XMLEventReader getXmlEventReader(GZIPInputStream xmlGzipInputStream, String encoding)
 694             throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
 695         return getXmlEventReader(new InputStreamReader(xmlGzipInputStream, encoding));
 696     }
 697 
 698     /**
 699      * 获得Event方式的XML解析器(事件读取器对象)
 700      * 
 701      * @param xmlFileInputStream
 702      * @return
 703      * @throws FileNotFoundException
 704      * @throws XMLStreamException
 705      * @throws UnsupportedEncodingException
 706      */
 707     public static XMLEventReader getXmlEventReader(FileInputStream xmlFileInputStream)
 708             throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
 709         return getXmlEventReader(xmlFileInputStream, "UTF-8");
 710     }
 711 
 712     /**
 713      * 获得Event方式的XML解析器(事件读取器对象)
 714      * 
 715      * @param xmlFileInputStream
 716      * @param encoding
 717      * @return
 718      * @throws FileNotFoundException
 719      * @throws XMLStreamException
 720      * @throws UnsupportedEncodingException
 721      */
 722     public static XMLEventReader getXmlEventReader(FileInputStream xmlFileInputStream, String encoding)
 723             throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
 724         return getXmlEventReader(new InputStreamReader(xmlFileInputStream, encoding));
 725     }
 726 
 727     /**
 728      * 获得Event方式的XML解析器(事件读取器对象)
 729      * 
 730      * @param xmlInputStreamReader
 731      * @return
 732      * @throws FileNotFoundException
 733      * @throws XMLStreamException
 734      */
 735     public static XMLEventReader getXmlEventReader(InputStreamReader xmlInputStreamReader)
 736             throws FileNotFoundException, XMLStreamException {
 737         return getXmlEventReader((Reader) xmlInputStreamReader);
 738     }
 739 
 740     /**
 741      * 获得Event方式的XML解析器(事件读取器对象)
 742      */
 743     public static XMLEventReader getXmlEventReader(FileReader xmlFileReader) throws FileNotFoundException, XMLStreamException {
 744         return getXmlEventReader((Reader) xmlFileReader);
 745     }
 746 
 747     /**
 748      * 获得Event方式的XML解析器(事件读取器对象)
 749      * 
 750      * @param xmlStringReader
 751      * @return
 752      * @throws FileNotFoundException
 753      * @throws XMLStreamException
 754      */
 755     public static XMLEventReader getXmlEventReader(StringReader xmlStringReader)
 756             throws FileNotFoundException, XMLStreamException {
 757         return getXmlEventReader((Reader) xmlStringReader);
 758     }
 759 
 760     /**
 761      * 获得Event方式的XML解析器(事件读取器对象)
 762      * 
 763      * @param xmlReader
 764      * @return
 765      * @throws FileNotFoundException
 766      * @throws XMLStreamException
 767      */
 768     public static XMLEventReader getXmlEventReader(Reader xmlReader) throws FileNotFoundException, XMLStreamException {
 769         return XMLInputFactory.newInstance().createXMLEventReader(xmlReader);
 770     }
 771 
 772     /**
 773      * 获得Event方式的XML解析器(事件读取器对象),支持过滤器
 774      * 
 775      * @param xmlFilePath
 776      *            XML文件路径 例如:String xmlFilePath = App.class.getResource("/").getFile() + "users.xml";
 777      * @param eventFilter
 778      *            事件式过滤器
 779      * @return
 780      * @throws XMLStreamException
 781      * @throws FileNotFoundException
 782      * @throws UnsupportedEncodingException
 783      */
 784     public static XMLEventReader getXmlEventReader(String xmlFilePath, EventFilter eventFilter)
 785             throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
 786         return getXmlEventReader(xmlFilePath, "UTF-8", eventFilter);
 787     }
 788 
 789     /**
 790      * 获得Event方式的XML解析器(事件读取器对象),支持过滤器
 791      * 
 792      * @param xmlFilePath
 793      * @param encoding
 794      * @param eventFilter
 795      * @return
 796      * @throws FileNotFoundException
 797      * @throws XMLStreamException
 798      * @throws UnsupportedEncodingException
 799      */
 800     public static XMLEventReader getXmlEventReader(String xmlFilePath, String encoding, EventFilter eventFilter)
 801             throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
 802         return getXmlEventReader(new FileInputStream(xmlFilePath), encoding, eventFilter);
 803     }
 804 
 805     /**
 806      * 获得Event方式的XML解析器(事件读取器对象),支持过滤器
 807      * 
 808      * @param xmlFile
 809      * @param eventFilter
 810      * @return
 811      * @throws FileNotFoundException
 812      * @throws XMLStreamException
 813      * @throws UnsupportedEncodingException
 814      */
 815     public static XMLEventReader getXmlEventReader(File xmlFile, EventFilter eventFilter)
 816             throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
 817         return getXmlEventReader(xmlFile, "UTF-8", eventFilter);
 818     }
 819 
 820     /**
 821      * 获得Event方式的XML解析器(事件读取器对象),支持过滤器
 822      * 
 823      * @param xmlFile
 824      * @param encoding
 825      * @param eventFilter
 826      * @return
 827      * @throws FileNotFoundException
 828      * @throws XMLStreamException
 829      * @throws UnsupportedEncodingException
 830      */
 831     public static XMLEventReader getXmlEventReader(File xmlFile, String encoding, EventFilter eventFilter)
 832             throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
 833         return getXmlEventReader(new FileInputStream(xmlFile), encoding, eventFilter);
 834     }
 835 
 836     /**
 837      * 获得Event方式的XML解析器(事件读取器对象),支持过滤器
 838      * 
 839      * @param xmlFileInputStream
 840      * @param eventFilter
 841      * @return
 842      * @throws FileNotFoundException
 843      * @throws XMLStreamException
 844      * @throws UnsupportedEncodingException
 845      */
 846     public static XMLEventReader getXmlEventReader(FileInputStream xmlFileInputStream, EventFilter eventFilter)
 847             throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
 848         return getXmlEventReader(xmlFileInputStream, "UTF-8", eventFilter);
 849     }
 850 
 851     /**
 852      * 获得Event方式的XML解析器(事件读取器对象),支持过滤器
 853      * 
 854      * @param xmlFileInputStream
 855      * @param encoding
 856      * @param eventFilter
 857      * @return
 858      * @throws FileNotFoundException
 859      * @throws XMLStreamException
 860      * @throws UnsupportedEncodingException
 861      */
 862     public static XMLEventReader getXmlEventReader(FileInputStream xmlFileInputStream, String encoding, EventFilter eventFilter)
 863             throws FileNotFoundException, XMLStreamException,
 864             UnsupportedEncodingException {
 865         return getXmlEventReader(new InputStreamReader(xmlFileInputStream, encoding), eventFilter);
 866     }
 867 
 868     /**
 869      * 获得Event方式的XML解析器(事件读取器对象),支持过滤器
 870      * 
 871      * @param xmlInputStreamReader
 872      * @param eventFilter
 873      * @return
 874      * @throws FileNotFoundException
 875      * @throws XMLStreamException
 876      */
 877     public static XMLEventReader getXmlEventReader(InputStreamReader xmlInputStreamReader, EventFilter eventFilter)
 878             throws FileNotFoundException, XMLStreamException {
 879         return getXmlEventReader((Reader) xmlInputStreamReader, eventFilter);
 880     }
 881 
 882     /**
 883      * 获得Event方式的XML解析器(事件读取器对象),支持过滤器
 884      * 
 885      * @param xmlFileReader
 886      * @param eventFilter
 887      * @return
 888      * @throws FileNotFoundException
 889      * @throws XMLStreamException
 890      */
 891     public static XMLEventReader getXmlEventReader(FileReader xmlFileReader, EventFilter eventFilter)
 892             throws FileNotFoundException, XMLStreamException {
 893         return getXmlEventReader((Reader) xmlFileReader, eventFilter);
 894     }
 895 
 896     /**
 897      * 获得Event方式的XML解析器(事件读取器对象),支持过滤器 如果是XML字符串,建议使用JAXB方式直接得到java对象。 不建议使用STAX方式拉取数据,除非是XML字符串信息很大或者需要每一条每一条的读取XML字符串里面的元素进行针对性的操作,否则不建议使用。
 898      * 
 899      * @param xmlStringReader
 900      * @param eventFilter
 901      * @return
 902      * @throws FileNotFoundException
 903      * @throws XMLStreamException
 904      */
 905     public static XMLEventReader getXmlEventReader(StringReader xmlStringReader, EventFilter eventFilter)
 906             throws FileNotFoundException, XMLStreamException {
 907         return getXmlEventReader((Reader) xmlStringReader, eventFilter);
 908     }
 909 
 910     /**
 911      * 获得Event方式的XML解析器(事件读取器对象),支持过滤器
 912      * 
 913      * @param xmlReader
 914      * @param eventFilter
 915      * @return
 916      * @throws FileNotFoundException
 917      * @throws XMLStreamException
 918      */
 919     public static XMLEventReader getXmlEventReader(Reader xmlReader, EventFilter eventFilter)
 920             throws FileNotFoundException, XMLStreamException {
 921         XMLEventReader xmlEventFilterReader = null;
 922         XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
 923         XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(xmlReader);
 924         xmlEventFilterReader = xmlInputFactory.createFilteredReader(xmlEventReader, eventFilter);
 925         return xmlEventFilterReader;
 926     }
 927 
 928     /**
 929      * 获得Event方式的XML解析器(事件读取器对象),支持过滤器
 930      * 
 931      * @param xmlEventReader
 932      *            Event方式的XML解析器
 933      * @param eventFilter
 934      *            事件式过滤器
 935      * @return
 936      * @throws XMLStreamException
 937      */
 938     public static XMLEventReader getXmlEventReader(XMLEventReader xmlEventReader, EventFilter eventFilter)
 939             throws XMLStreamException {
 940         // 创建基于迭代器的指针读取器对象
 941         return XMLInputFactory.newInstance().createFilteredReader(xmlEventReader, eventFilter);
 942     }
 943 
 944     /**
 945      * 释放Event方式的XML解析器对象所占用的内存空间
 946      * 
 947      * @param xmlEventReader
 948      * @throws XMLStreamException
 949      */
 950     public static void close(XMLEventReader xmlEventReader) throws XMLStreamException {
 951         if (xmlEventReader != null) {
 952             xmlEventReader.close();
 953             xmlEventReader = null;
 954         }
 955     }
 956 
 957     public static XMLStreamWriter getXmlStreamWriter(String xmlFilePath) throws XMLStreamException, IOException {
 958         return getXmlStreamWriter(xmlFilePath, "UTF-8", "1.0");
 959     }
 960 
 961     public static XMLStreamWriter getXmlStreamWriter(String xmlFilePath, String encoding, String version)
 962             throws XMLStreamException, IOException {
 963         return getXmlStreamWriter(new File(xmlFilePath), encoding, version);
 964     }
 965 
 966     public static XMLStreamWriter getXmlStreamWriter(File xmlFile) throws XMLStreamException, IOException {
 967         return getXmlStreamWriter(xmlFile, "UTF-8", "1.0");
 968     }
 969 
 970     public static XMLStreamWriter getXmlStreamWriter(File file, String encoding, String version)
 971             throws XMLStreamException, IOException {
 972         if (file.isFile() && file.exists()) {
 973             file.delete();
 974         } else {
 975             File dir = new File(file.getParent());
 976             if (!dir.exists()) {
 977                 dir.mkdirs();
 978             }
 979             dir = null;
 980         }
 981         // if (file.getName().endsWith(".gz")) {
 982         // return getXmlStreamWriter(new GZIPOutputStream(new FileOutputStream(file)), encoding, version);
 983         // } else {
 984         return getXmlStreamWriter(new FileOutputStream(file), encoding, version);
 985         // }
 986     }
 987 
 988     public static XMLStreamWriter getXmlStreamWriter(FileOutputStream fileOutputSteam) throws XMLStreamException {
 989         return getXmlStreamWriter(fileOutputSteam, "UTF-8", "1.0");
 990     }
 991 
 992     public static XMLStreamWriter getXmlStreamWriter(FileOutputStream fileOutputSteam, String encoding, String version)
 993             throws XMLStreamException {
 994         return getXmlStreamWriter(new BufferedOutputStream(fileOutputSteam, 20480), encoding, version);
 995     }
 996 
 997     // public static XMLStreamWriter getXmlStreamWriter(GZIPOutputStream gzipOutputSteam) throws XMLStreamException{
 998     // return getXmlStreamWriter(gzipOutputSteam, "UTF-8", "1.0");
 999     // }
1000     //
1001     // public static XMLStreamWriter getXmlStreamWriter(GZIPOutputStream gzipOutputSteam, String encoding, String version) throws XMLStreamException {
1002     // return getXmlStreamWriter(new BufferedOutputStream(gzipOutputSteam, 20480), encoding, version);
1003     // }
1004 
1005     public static XMLStreamWriter getXmlStreamWriter(PrintStream printStream) throws XMLStreamException {
1006         return getXmlStreamWriter(printStream, "UTF-8", "1.0");
1007     }
1008 
1009     public static XMLStreamWriter getXmlStreamWriter(PrintStream printStream, String encoding, String version)
1010             throws XMLStreamException {
1011         return getXmlStreamWriter(new BufferedOutputStream(printStream, 20480), encoding, version);
1012     }
1013 
1014     public static XMLStreamWriter getXmlStreamWriter(BufferedOutputStream bufferedOutpuStream) throws XMLStreamException {
1015         return getXmlStreamWriter(bufferedOutpuStream, "UTF-8", "1.0");
1016     }
1017 
1018     public static XMLStreamWriter getXmlStreamWriter(BufferedOutputStream bufferedOutpuStream, String encoding, String version)
1019             throws XMLStreamException {
1020         return getXmlStreamWriter((OutputStream) bufferedOutpuStream, encoding, version);
1021     }
1022 
1023     public static XMLStreamWriter getXmlStreamWriter(OutputStream outputStream) throws XMLStreamException {
1024         return getXmlStreamWriter(outputStream, "UTF-8", "1.0");
1025     }
1026 
1027     public static XMLStreamWriter getXmlStreamWriter(OutputStream outputStream, String encoding, String version)
1028             throws XMLStreamException {
1029         XMLStreamWriter xmlStreamWriter = null;
1030         XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
1031         xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(outputStream, encoding);
1032         xmlStreamWriter = new IndentingXMLStreamWriter(xmlStreamWriter);
1033         xmlStreamWriter.writeStartDocument(encoding, version);
1034         return xmlStreamWriter;
1035     }
1036 
1037     /**
1038      * 格式化输出Reader
1039      * 
1040      * @param xmlEventReader
1041      * @param outputStream
1042      * @throws XMLStreamException
1043      * @throws TransformerException
1044      */
1045     public static void outputXmlReader(XMLEventReader xmlEventReader, OutputStream outputStream)
1046             throws XMLStreamException, TransformerException {
1047         outputXmlReader(xmlEventReader, outputStream, "UTF-8", "1.0");
1048     }
1049 
1050     /**
1051      * 格式化输出Reader
1052      * 
1053      * @param xmlEventReader
1054      * @param outputStream
1055      * @param encoding
1056      * @param version
1057      * @throws XMLStreamException
1058      * @throws TransformerException
1059      */
1060     public static void outputXmlReader(XMLEventReader xmlEventReader, OutputStream outputStream, String encoding, String version)
1061             throws XMLStreamException, TransformerException {
1062         XMLStreamWriter xmlStreamWriter = null;
1063         XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
1064         xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(outputStream, encoding);
1065         TransformerFactory transformerFactory = TransformerFactory.newInstance();
1066         Transformer transformer = transformerFactory.newTransformer();
1067         transformer.setOutputProperty(OutputKeys.INDENT, "yes");// 写完一行之后是否换行
1068         transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");// 设置字符编码。
1069         transformer.transform(new StAXSource(xmlEventReader), new StAXResult(xmlStreamWriter));
1070     }
1071 
1072     public static XMLStreamWriter geteXmlStreamWriter(OutputStreamWriter outpuStreamWriter) throws XMLStreamException {
1073         return getXmlStreamWriter(outpuStreamWriter, "UTF-8", "1.0");
1074     }
1075 
1076     public static XMLStreamWriter geteXmlStreamWriter(OutputStreamWriter outpuStreamWriter, String encoding, String version)
1077             throws XMLStreamException {
1078         return getXmlStreamWriter((Writer) outpuStreamWriter, encoding, version);
1079     }
1080 
1081     public static XMLStreamWriter geteXmlStreamWriter(StringWriter stringWriter) throws XMLStreamException {
1082         return getXmlStreamWriter(stringWriter, "UTF-8", "1.0");
1083     }
1084 
1085     public static XMLStreamWriter geteXmlStreamWriter(StringWriter stringWriter, String encoding, String version)
1086             throws XMLStreamException {
1087         return getXmlStreamWriter((Writer) stringWriter, encoding, version);
1088     }
1089 
1090     public static XMLStreamWriter geteXmlStreamWriter(PrintWriter printWriter) throws XMLStreamException {
1091         return getXmlStreamWriter((Writer) printWriter, "UTF-8", "1.0");
1092     }
1093 
1094     public static XMLStreamWriter geteXmlStreamWriter(PrintWriter printWriter, String encoding, String version)
1095             throws XMLStreamException {
1096         return getXmlStreamWriter((Writer) printWriter, encoding, version);
1097     }
1098 
1099     public static XMLStreamWriter getXmlStreamWriter(Writer xmlWriter, String encoding, String version)
1100             throws XMLStreamException {
1101         XMLStreamWriter xmlStreamWriter = null;
1102         XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
1103         xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(xmlWriter);
1104         xmlStreamWriter = new IndentingXMLStreamWriter(xmlStreamWriter);// 使用这个类进行格式化XML输出
1105         xmlStreamWriter.writeStartDocument(encoding, version);
1106         return xmlStreamWriter;
1107     }
1108 
1109     /**
1110      * 写入根元素或者是开始元素的名称。例如:<channel>
1111      * 
1112      * @param xmlStreamWriter
1113      * @param localName
1114      *            channel
1115      * @throws XMLStreamException
1116      */
1117     public static void writeStartElement(XMLStreamWriter xmlStreamWriter, String localName) throws XMLStreamException {
1118         xmlStreamWriter.writeStartElement(localName);
1119     }
1120 
1121     /**
1122      * 写入带有命名空间的XML标签。例如: <rss xmlns:g="http://base.google.com/ns/1.0">
1123      * 
1124      * @param xmlStreamWriter
1125      * @param localName
1126      *            rss
1127      * @param prefix
1128      *            g
1129      * @param namespaceURI
1130      *            http://base.google.com/ns/1.0
1131      * @throws XMLStreamException
1132      */
1133     public static void writeStartElement(XMLStreamWriter xmlStreamWriter, String localName, String prefix, String namespaceURI)
1134             throws XMLStreamException {
1135         xmlStreamWriter.writeStartElement(localName);
1136         // xmlStreamWriter.writeAttribute(XMLConstants.XML_NS_URI, prefix, namespaceURI);
1137         xmlStreamWriter.writeNamespace(prefix, namespaceURI);
1138     }
1139 
1140     public static <T> Marshaller getMarshaller(Class<T> elementType) throws JAXBException {
1141         JAXBContext jaxbContext = JAXBContext.newInstance(elementType);
1142         Marshaller marshaller = jaxbContext.createMarshaller();
1143         marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// //编码格式
1144         // marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);// 注释掉是否格式化生成的xml串没用有wangyunpeng,改从IndentingXMLStreamWriter这里设置格式化。
1145         marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);// 是否省略xml头声明信息
1146         return marshaller;
1147     }
1148 
1149     /**
1150      * 要写入XML元素信息
1151      * 
1152      * @param xmlStreamWriter
1153      * @param marshaller
1154      * @param elementName
1155      * @param element
1156      * @throws JAXBException
1157      * @throws TransformerException
1158      * @throws IOException
1159      * @throws XMLStreamException
1160      */
1161     public static <T> void writeElement(XMLStreamWriter xmlStreamWriter, Marshaller marshaller, String elementName, T element)
1162             throws JAXBException, TransformerException, IOException,
1163             XMLStreamException {
1164         writeElement(xmlStreamWriter, marshaller, elementName, element, Boolean.valueOf(true));
1165     }
1166 
1167     /**
1168      * 要写入XML元素信息
1169      * 
1170      * @param xmlStreamWriter
1171      * @param marshaller
1172      * @param elementName
1173      * @param element
1174      * @param useCData
1175      *            是否使用CData方式输出
1176      * @throws JAXBException
1177      * @throws TransformerException
1178      * @throws IOException
1179      * @throws XMLStreamException
1180      */
1181     @SuppressWarnings("unchecked")
1182     public static <T> void writeElement(XMLStreamWriter xmlStreamWriter, Marshaller marshaller, String elementName, T element,
1183             Boolean useCData) throws JAXBException, TransformerException,
1184                     IOException, XMLStreamException {
1185         JAXBElement<T> jaxbElement = new JAXBElement<T>(new QName(elementName), (Class<T>) element.getClass(), element);
1186         if (useCData.booleanValue()) {
1187             xmlStreamWriter = new CDataXMLStreamWriter(xmlStreamWriter);// 使用CData方式输出
1188         }
1189         marshaller.marshal(jaxbElement, xmlStreamWriter);
1190     }
1191 
1192     /**
1193      * 释放XMLStreamWriter对象所占用的内存
1194      * 
1195      * @param xmlStreamWriter
1196      * @throws XMLStreamException
1197      */
1198     public static void close(XMLStreamWriter xmlStreamWriter) throws XMLStreamException {
1199         xmlStreamWriter.writeEndDocument();
1200         xmlStreamWriter.flush();
1201         xmlStreamWriter.close();
1202         xmlStreamWriter = null;
1203     }
1204 
1205     /*
1206      * JAXB + StAX 能够快速读取XML中某一个XML对象信息
1207      */
1208 
1209     /**
1210      * 快速定位到XML中的某一个元素名称上
1211      * 
1212      * @param xmlEventReader
1213      *            Event方式的XML解析器
1214      * @param skipElementName
1215      *            某一个XML元素的名称
1216      * @return
1217      * @throws XMLStreamException
1218      *             返回只会读取XML元素的Event方式的XML解析器
1219      */
1220     public static XMLEventReader skipFirstElements(XMLEventReader xmlEventReader, String skipElementName)
1221             throws XMLStreamException {
1222         XMLEventReader xmlEventFilterReader = getXmlEventReader(xmlEventReader, new EventFilter() {
1223             @Override
1224             public boolean accept(XMLEvent event) {
1225                 return event.isStartElement();
1226             }
1227         });
1228 
1229         while (xmlEventFilterReader.hasNext()) {
1230             XMLEvent xmlEvent = xmlEventFilterReader.peek();
1231             if (xmlEvent.isStartElement()) {
1232                 StartElement startElement = xmlEvent.asStartElement();
1233                 String elementName = startElement.getName().getLocalPart();
1234                 if (elementName.equals(skipElementName)) {
1235                     break;
1236                 }
1237             }
1238             xmlEventFilterReader.nextEvent();
1239         }
1240         return xmlEventFilterReader;
1241     }
1242 
1243     /**
1244      * 读取所有指定名称的XML元素里面的所有内容,并返回它的java类型的对象集合信息
1245      * 
1246      * @param xmlEventReader
1247      * @param skipElementName
1248      * @param cls
1249      * @return
1250      * @throws JAXBException
1251      * @throws XMLStreamException
1252      */
1253     @SuppressWarnings("unchecked")
1254     public static <T> List<T> getAllJavaObjectByXMLElement(XMLEventReader xmlEventReader, String elementName, Class<T> cls)
1255             throws JAXBException, XMLStreamException {
1256         List<T> list = new ArrayList<T>();
1257         XMLEventReader xmlEventFilterReader = null;
1258         try {
1259             JAXBContext context = JAXBContext.newInstance(cls);
1260             Unmarshaller unmarshaller = context.createUnmarshaller();
1261             xmlEventFilterReader = skipFirstElements(xmlEventReader, elementName);
1262             while (xmlEventFilterReader.peek() != null) {
1263                 Object object = unmarshaller.unmarshal(xmlEventReader);
1264                 if (cls.isInstance(object)) {
1265                     list.add((T) object);
1266                 }
1267             }
1268         } catch (JAXBException | XMLStreamException e) {
1269             throw e;
1270         } finally {
1271             if (xmlEventFilterReader != null) {
1272                 xmlEventFilterReader.close();
1273                 xmlEventFilterReader = null;
1274             }
1275         }
1276         return list;
1277     }
1278 
1279     /**
1280      * 将每一个指定名称的XML元素转成java类型的对象,然后在执行action方法做进一步的业务处理,目的是为了解决批量处理全部指定名称的XML元素内容转成java对象集合后内存溢出的问题。 (将每一个指定名称XML元素逐个转成java类型的对象,然后在逐个处理这个java类型的对象)
1281      * 
1282      * @param xmlEventReader
1283      * @param elementName
1284      * @param cls
1285      * @param action1
1286      * 
1287      * @throws JAXBException
1288      * @throws XMLStreamException
1289      */
1290     @SuppressWarnings("unchecked")
1291     public static <T> void eachOfXmlElementConvertJavaObjectHandler(XMLEventReader xmlEventReader, String elementName,
1292             Class<T> cls, Action1<T> action1) throws JAXBException, XMLStreamException {
1293         XMLEventReader xmlEventFilterReader = null;
1294         try {
1295             JAXBContext context = JAXBContext.newInstance(cls);
1296             Unmarshaller unmarshaller = context.createUnmarshaller();
1297             xmlEventFilterReader = skipFirstElements(xmlEventReader, elementName);
1298             while (xmlEventFilterReader.peek() != null) {
1299                 Object object = unmarshaller.unmarshal(xmlEventReader);
1300                 if (cls.isInstance(object)) {
1301                     action1.action((T) object);
1302                 }
1303             }
1304         } catch (JAXBException | XMLStreamException e) {
1305             throw e;
1306         } finally {
1307             if (xmlEventFilterReader != null) {
1308                 xmlEventFilterReader.close();
1309                 xmlEventFilterReader = null;
1310             }
1311         }
1312     }
1313 
1314     /**
1315      * 将每一个指定名称的XML元素转成java类型的对象,然后在执行action方法做进一步的业务处理,目的是为了解决批量处理全部指定名称的XML元素内容转成java对象集合后内存溢出的问题。 (将每一个指定名称XML元素逐个转成java类型的对象,然后在逐个处理这个java类型的对象)
1316      * 
1317      * @param xmlEventReader
1318      * @param elementName
1319      * @param cls
1320      * @param func1
1321      *            如果func1的返回值为false就退出循环
1322      * @throws JAXBException
1323      * @throws XMLStreamException
1324      */
1325     @SuppressWarnings("unchecked")
1326     public static <T> void eachOfXmlElementConvertJavaObjectHandler(XMLEventReader xmlEventReader, String elementName,
1327             Class<T> cls, Func1<T, Boolean> func1) throws JAXBException, XMLStreamException {
1328         XMLEventReader xmlEventFilterReader = null;
1329         try {
1330             JAXBContext context = JAXBContext.newInstance(cls);
1331             Unmarshaller unmarshaller = context.createUnmarshaller();
1332             xmlEventFilterReader = skipFirstElements(xmlEventReader, elementName);
1333             while (xmlEventFilterReader.peek() != null) {
1334                 Object object = unmarshaller.unmarshal(xmlEventReader);
1335                 if (cls.isInstance(object)) {
1336                     if (!func1.func((T) object).booleanValue()) {
1337                         break;
1338                     }
1339                 }
1340             }
1341         } catch (JAXBException | XMLStreamException e) {
1342             throw e;
1343         } finally {
1344             if (xmlEventFilterReader != null) {
1345                 xmlEventFilterReader.close();
1346                 xmlEventFilterReader = null;
1347             }
1348         }
1349     }
1350 }
XmlHelper.java
复制代码

将java集合对象写入xml文件中

复制代码
 1 final XMLStreamWriter writer = XmlHelper.getXmlStreamWriter(xmlFilePath);
 2 XmlHelper.writeStartElement(writer, "rss", "g", "http://base.google.com/ns/1.0");
 3 XmlHelper.writeStartElement(writer, "channel");
 4 
 5 final Marshaller marshaller = XmlHelper.getMarshaller(FacebookFeedModel.class);
 6 writeItem(writer, marshaller, feedModelList, "item");
 7 
 8 XmlHelper.close(writer);
 9 GZipHelper.compress(xmlFilePath, true);
10 
11 
12 
13 /**
14   * 生成XML文件
15   */
16 public <T> Boolean writeItem(XMLStreamWriter writer, Marshaller marshaller, List<T> itemList, String elementName) {
17         Boolean result = Boolean.valueOf(true);
18         for (T item : itemList) {
19             try {
20                 XmlHelper.writeElement(writer, marshaller, elementName, item);
21             } catch (JAXBException | TransformerException | IOException | XMLStreamException e) {
22                 e.printStackTrace();
23                 result = Boolean.valueOf(false);
24             }
25         }
26         itemList.clear();
27         return result;
28     }
write xml file
复制代码

读取xml文件,返回java集合对象

复制代码
1 XMLEventReader xmlEventReader = XmlHelper.getXmlEventReader(feedFileNameModel.getFeedFile());
2 try {
3     List<ItemModel> itemModelList = XmlHelper.getAllJavaObjectByXMLElement(xmlEventReader, "item", ItemModel.class);
4 } finally {
5     XmlHelper.close(xmlEventReader);
6 }
reader xml file
复制代码

读取xml文件,自定义处理集合里面每一个对象的信息,

复制代码
 1 XMLEventReader xmlEventReader = XmlHelper.getXmlEventReader(feedFileNameModel.getFeedFile());
 2 try {
 3     XmlHelper.eachOfXmlElementConvertJavaObjectHandler(xmlEventReader, "item", ItemModel.class, new Action1<ItemModel>() {
 4         @Override
 5         public void action(ItemModel itemModel) {
 6             String offerId = loading(connection, counterMap, feedFileNameModel, itemModel);
 7             if (offerIdList != null && StringUtils.isNotEmpty(offerId)) {
 8                 offerIdList.remove(offerId);
 9             }
10         }
11     });
12 } finally {
13     XmlHelper.close(xmlEventReader);
14 }
reader xml file custom handler
复制代码

java对gzip文件的操作

复制代码
  1 package tb.helper;
  2 
  3 import org.apache.commons.codec.binary.Base64;
  4 
  5 import java.io.*;
  6 import java.nio.charset.Charset;
  7 import java.util.zip.GZIPInputStream;
  8 import java.util.zip.GZIPOutputStream;
  9 
 10 /**
 11  * @author wangyunpeng Gzip文件和数据压缩
 12  */
 13 public class GZipHelper {
 14 
 15     public static final int BUFFER = 1024;
 16     public static final String EXT = ".gz";
 17 
 18     /**
 19      * 数据Gzip压缩
 20      *
 21      * @author wangyunpeng
 22      * @param uncompressData 未压缩的字符串
 23      * @return 压缩后的字符串(Base64格式)
 24      * @throws IOException
 25      * @since JDK 1.7.79
 26      */
 27     public static String compresses(String uncompressData) throws IOException {
 28         byte[] compressDatas = compress(uncompressData.getBytes(Charset.forName(IOHelper.DEFAULT_ENCODING)));
 29         return Base64.encodeBase64String(compressDatas);
 30     }
 31 
 32     /**
 33      * 数据Gzip压缩
 34      * 
 35      * @param uncompressDatas
 36      *            未压缩的字节数组
 37      * @return 压缩后的字节数组
 38      * @throws Exception
 39      */
 40     public static byte[] compress(byte[] uncompressDatas) throws IOException {
 41         byte[] compressDatas = null;
 42         try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(uncompressDatas)) {
 43             try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
 44                 compress(byteArrayInputStream, byteArrayOutputStream);
 45                 compressDatas = byteArrayOutputStream.toByteArray();
 46                 byteArrayOutputStream.flush();
 47             }
 48         }
 49         return compressDatas;
 50     }
 51 
 52     /**
 53      * 数据压缩
 54      * 
 55      * @param inputStream
 56      *            未压缩的输入流
 57      * @param outputStream
 58      *            压缩后的输出流
 59      * @throws Exception
 60      */
 61     public static void compress(InputStream inputStream, OutputStream outputStream) throws IOException {
 62         try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream)) {
 63             int count;
 64             byte data[] = new byte[BUFFER];
 65             while ((count = inputStream.read(data, 0, BUFFER)) != -1) {
 66                 gzipOutputStream.write(data, 0, count);
 67             }
 68             gzipOutputStream.finish();
 69             gzipOutputStream.flush();
 70         }
 71     }
 72 
 73     /**
 74      * 文件压缩
 75      * 
 76      * @param filePath
 77      *            要压缩的文件路径
 78      * @return 压缩后的文件路径
 79      * @throws Exception
 80      */
 81     public static String compress(String filePath) throws IOException {
 82         return compress(filePath, true);
 83     }
 84 
 85     /**
 86      * 文件压缩
 87      * 
 88      * @param uncompressFilePath
 89      *            要压缩的文件路径
 90      * @param isDelete
 91      *            是否删除原始文件
 92      * @return 压缩后的文件路径
 93      * @throws Exception
 94      */
 95     public static String compress(String uncompressFilePath, boolean isDelete) throws IOException {
 96         File file = new File(uncompressFilePath);
 97         String compressFilePath = compress(file, isDelete);
 98         file = null;
 99         return compressFilePath;
100     }
101 
102     /**
103      * 文件压缩
104      * 
105      * @param uncompressFile
106      *            要压缩的文件路径
107      * @return 压缩后的文件路径
108      * @throws Exception
109      */
110     public static String compress(File uncompressFile) throws IOException {
111         return compress(uncompressFile, true);
112     }
113 
114     /**
115      * 文件压缩
116      * 
117      * @param uncompressFile
118      *            要压缩的文件
119      * @param isDelete
120      *            是否删除原文件
121      * @return 压缩后的文件路径
122      * @throws Exception
123      */
124     public static String compress(File uncompressFile, boolean isDelete) throws IOException {
125         String compressFilePath = uncompressFile.getPath() + EXT;
126         try (FileInputStream fileInputStream = new FileInputStream(uncompressFile)) {
127             try (FileOutputStream fileOutputStream = new FileOutputStream(compressFilePath)) {
128                 compress(fileInputStream, fileOutputStream);
129                 fileOutputStream.flush();
130                 if (isDelete) {
131                     uncompressFile.delete();
132                 }
133             }
134         }
135         return compressFilePath;
136     }
137 
138     /**
139      * 数据解压缩
140      *
141      * @author wangyunpeng
142      * @param compressData 压缩后的字符串(Base64格式)
143      * @return 未压缩的字符串
144      * @throws IOException
145      * @since JDK 1.7.79
146      */
147     public static String decompresses(String compressData) throws IOException {
148         byte[] uncompressDatas = decompress(Base64.decodeBase64(compressData));
149         return new String(uncompressDatas, Charset.forName(IOHelper.DEFAULT_ENCODING));
150     }
151 
152     /**
153      * 数据解压缩
154      * 
155      * @param compressDatas 压缩后的字节数组
156      * @return 未压缩的字节数组
157      * @throws Exception
158      */
159     public static byte[] decompress(byte[] compressDatas) throws IOException {
160         byte[] uncompressDatas = null;
161         try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(compressDatas)) {
162             try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
163                 // 解压缩
164                 decompress(byteArrayInputStream, byteArrayOutputStream);
165                 uncompressDatas = byteArrayOutputStream.toByteArray();
166                 byteArrayOutputStream.flush();
167             }
168         }
169         return uncompressDatas;
170     }
171 
172     /**
173      * 数据解压缩
174      * 
175      * @param inputStream
176      * @param outputStream
177      * @throws Exception
178      */
179     public static void decompress(InputStream inputStream, OutputStream outputStream) throws IOException {
180         try (GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream)) {
181             int count;
182             byte data[] = new byte[BUFFER];
183             while ((count = gzipInputStream.read(data, 0, BUFFER)) != -1) {
184                 outputStream.write(data, 0, count);
185             }
186         }
187     }
188 
189     /**
190      * 文件解压缩
191      * 
192      * @param compressFile
193      * @return 解压缩后的文件路径
194      * @throws Exception
195      */
196     public static String decompress(File compressFile) throws IOException {
197         return decompress(compressFile, true);
198     }
199 
200     /**
201      * 文件解压缩
202      * 
203      * @param compressFile
204      * @param isDelete
205      *            是否删除原始文件
206      * @return 解压缩后的文件路径
207      * @throws Exception
208      */
209     public static String decompress(File compressFile, boolean isDelete) throws IOException {
210         String uncompressFilePath = null;
211         try (FileInputStream fileInputStream = new FileInputStream(compressFile)) {
212             uncompressFilePath = compressFile.getPath().replace(EXT, "");
213             try (FileOutputStream fileOutputStream = new FileOutputStream(uncompressFilePath)) {
214                 decompress(fileInputStream, fileOutputStream);
215                 fileOutputStream.flush();
216                 if (isDelete) {
217                     compressFile.delete();
218                 }
219             }
220         }
221         return uncompressFilePath;
222     }
223 
224     /**
225      * 文件解压缩
226      * 
227      * @param compressFilePath
228      *            要解压缩的文件路径
229      * @return 解压缩后的文件路径
230      * @throws Exception
231      */
232     public static String decompress(String compressFilePath) throws IOException {
233         return decompress(compressFilePath, true);
234     }
235 
236     /**
237      * 文件解压缩
238      * 
239      * @param compressFilePath
240      *            要解压缩的文件路径
241      * @param isDelete
242      *            是否删除原始文件
243      * @return 解压缩后的文件路径
244      * @throws Exception
245      */
246     public static String decompress(String compressFilePath, boolean isDelete) throws IOException {
247         File compressFile = new File(compressFilePath);
248         String uncompressFilePath = decompress(compressFile, isDelete);
249         compressFile = null;
250         return uncompressFilePath;
251     }
252 
253     private String inputStr = "zlex@zlex.org,snowolf@zlex.org,zlex.snowolf@zlex.org";
254 
255     //@Test
256     public final void testDataCompress() throws Exception {
257 
258         System.err.println("原文:\t" + inputStr);
259 
260         byte[] input = inputStr.getBytes();
261         System.err.println("长度:\t" + input.length);
262 
263         byte[] data = compress(input);
264         System.err.println("压缩后:\t");
265         System.err.println("长度:\t" + data.length);
266 
267         byte[] output = decompress(data);
268         String outputStr = new String(output);
269         System.err.println("解压缩后:\t" + outputStr);
270         System.err.println("长度:\t" + output.length);
271 
272     }
273 
274     //@Test
275     public final void testFileCompress() throws Exception {
276         FileOutputStream fos = new FileOutputStream("/data/filedata");
277         fos.write(inputStr.getBytes());
278         fos.flush();
279         fos.close();
280 
281         compress("/data/filedata", false);
282         decompress("/data/filedata.gz", false);
283 
284         File file = new File("/data/filedata");
285         FileInputStream fis = new FileInputStream(file);
286         DataInputStream dis = new DataInputStream(fis);
287 
288         byte[] data = new byte[(int) file.length()];
289         dis.readFully(data);
290 
291         fis.close();
292 
293         String outputStr = new String(data);
294         System.out.println(outputStr);
295     }
296 }
GZipHelper
复制代码

net core

How to stream XML fragments from an XmlReader (LINQ to XML)

复制代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Xml;
 6 using System.Xml.Linq;
 7 
 8 namespace ConsoleApp1
 9 {
10     class Program
11     {
12         static IEnumerable<XElement> StreamRootChildDoc(StringReader stringReader)
13         {
14             //XmlReader.Create(stream);
15             using (XmlReader reader = XmlReader.Create(stringReader))
16             {
17                 reader.MoveToContent();
18                 // Parse the file and display each of the nodes.
19                 while (reader.Read())
20                 {
21                     switch (reader.NodeType)
22                     {
23                         case XmlNodeType.Element:
24                             if (reader.Name == "Child")
25                             {
26                                 XElement el = XElement.ReadFrom(reader) as XElement;
27                                 if (el != null)
28                                     yield return el;
29                             }
30                             break;
31                     }
32                 }
33             }
34         }
35 
36         static void Main(string[] args)
37         {
38             string markup = @"<Root>
39                               <Child Key=""01"">
40                                 <GrandChild>aaa</GrandChild>
41                               </Child>
42                               <Child Key=""02"">
43                                 <GrandChild>bbb</GrandChild>
44                               </Child>
45                               <Child Key=""03"">
46                                 <GrandChild>ccc</GrandChild>
47                               </Child>
48                             </Root>";
49 
50             IEnumerable<string> grandChildData =
51                 from el in StreamRootChildDoc(new StringReader(markup))
52                 where (int)el.Attribute("Key") > 1
53                 select (string)el.Element("GrandChild");
54 
55             foreach (string str in grandChildData)
56             {
57                 Console.WriteLine(str);
58             }
59         }
60     }
61 }
Program
复制代码

 XmlHelper.cs

复制代码
  1 using System;
  2 using System.Collections.Generic;
  3 using System.IO;
  4 using System.Text;
  5 using System.Xml;
  6 using System.Xml.Linq;
  7 using System.Xml.Serialization;
  8 using System.Xml.XPath;
  9 
 10 namespace ConsoleApp1
 11 {
 12     /// <summary>
 13     /// XML帮助类
 14     /// </summary>
 15     public static class XmlHelper
 16     {
 17         /// <summary>
 18         /// 读取XML指定节点
 19         /// </summary>
 20         /// <param name="xmlFilePath">XML文件的路径</param>
 21         /// <param name="xpath">XPath路径</param>
 22         /// <returns></returns>
 23         public static string ReadXmlNode(string xmlFilePath, string xpath)
 24         {
 25             string result = string.Empty;
 26             try
 27             {
 28                 XPathDocument doc = new XPathDocument(xmlFilePath);
 29                 XPathNavigator nav = doc.CreateNavigator();
 30                 XPathNodeIterator ite = nav.Select(xpath);
 31                 ite.MoveNext();
 32                 result = ite.Current.Value;
 33                 ite = null;
 34                 nav = null;
 35                 doc = null;
 36             }
 37             catch (Exception ex)
 38             {
 39                 throw ex;
 40             }
 41             return result;
 42         }
 43         /// <summary>
 44         /// 读取XML指定节点集合
 45         /// </summary>
 46         /// <param name="xmlFilePath">XML文件的路径</param>
 47         /// <param name="xpath">XPath路径</param>
 48         /// <returns></returns>
 49         public static List<string> ReadXmlNodeList(string xmlFilePath, string xpath)
 50         {
 51             List<string> lists = null;
 52             try
 53             {
 54                 XPathDocument doc = new XPathDocument(xmlFilePath);
 55                 XPathNavigator nav = doc.CreateNavigator();
 56                 XPathNodeIterator ite = nav.Select(xpath);
 57                 foreach (XPathNavigator node in ite)
 58                 {
 59                     if (lists == null)
 60                         lists = new List<string>();
 61                     lists.Add(node.InnerXml);
 62                 }
 63                 ite = null;
 64                 nav = null;
 65                 doc = null;
 66             }
 67             catch (Exception ex)
 68             {
 69                 throw;
 70             }
 71             return lists;
 72         }
 73         /// <summary>
 74         /// 写入XML指定节点的值
 75         /// </summary>
 76         /// <param name="xmlFilePath">XML文件路径</param>
 77         /// <param name="xpath">XPath路径</param>
 78         /// <param name="newValue">改变的值</param>
 79         public static void WriteXmlNode(string xmlFilePath, string xpath, string newValue)
 80         {
 81             try
 82             {
 83                 XmlDocument doc = new XmlDocument();
 84                 doc.Load(xmlFilePath);
 85                 XmlNode node = doc.DocumentElement.SelectSingleNode(xpath);
 86                 node.InnerText = newValue;
 87                 doc.Save(xmlFilePath);
 88                 node = null;
 89                 doc = null;
 90             }
 91             catch (Exception ex)
 92             {
 93                 throw;
 94             }
 95         }
 96 
 97         public static XmlWriter GetXmlWriter(string outputFilePath)
 98         {
 99             return XmlWriter.Create(outputFilePath);
100         }
101 
102         public static XmlWriter GetXmlWriter(StringBuilder sb)
103         {
104             return XmlWriter.Create(sb);
105         }
106 
107         public static XmlWriter GetXmlWriter(Stream outpuStream)
108         {
109             return XmlWriter.Create(outpuStream);
110         }
111 
112         /// <summary>
113         /// 写入开始元素
114         /// </summary>
115         /// <param name="xmlWriter"></param>
116         /// <param name="elementName"></param>
117         public static void WriteStartElement(XmlWriter xmlWriter, String elementName)
118         {
119             xmlWriter.WriteStartElement(elementName);
120         }
121 
122         /// <summary>
123         /// 写入结束元素
124         /// </summary>
125         /// <param name="xmlWriter"></param>
126         public static void WriteEndElement(XmlWriter xmlWriter)
127         {
128             xmlWriter.WriteEndElement();
129         }
130 
131         /// <summary>
132         /// 要写入XML元素信息
133         /// </summary>
134         /// <typeparam name="T"></typeparam>
135         /// <param name="xmlWriter"></param>
136         /// <param name="elementName"></param>
137         /// <param name="obj"></param>
138         public static void WriteElement<T>(XmlWriter xmlWriter, String elementName, T obj)
139         {
140             XElement xElement = ToXElement<T>(obj);
141             xElement.WriteTo(xmlWriter);
142         }
143 
144         /// <summary>
145         /// 要写入XML元素信息
146         /// </summary>
147         /// <typeparam name="T"></typeparam>
148         /// <param name="xmlWriter"></param>
149         /// <param name="elementName"></param>
150         /// <param name="list"></param>
151         public static void WriteElement<T>(XmlWriter xmlWriter, String elementName, List<T> list)
152         {
153             foreach (T obj in list)
154             {
155                 WriteElement<T>(xmlWriter, elementName, obj);
156             }
157         }
158 
159         /// <summary>
160         /// 
161         /// </summary>
162         /// <param name="xmlContent"></param>
163         /// <returns></returns>
164         public static XmlReader GetXmlReader(string xmlContent)
165         {
166             return GetXmlReader(new StringReader(xmlContent));
167         }
168 
169         public static XmlReader GetXmlReader(StringReader stringReader)
170         {
171             XmlReader reader = XmlReader.Create(stringReader);
172             return reader;
173         }
174 
175         public static XmlReader GetXmlReader(Stream inputStream)
176         {
177             XmlReader reader = XmlReader.Create(inputStream);
178             return reader;
179         }
180 
181         /// <summary>
182         /// 将C#类型对象转成xml元素
183         /// </summary>
184         /// <typeparam name="T"></typeparam>
185         /// <param name="obj"></param>
186         /// <returns></returns>
187         public static XElement ToXElement<T>(T obj)
188         {
189             XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
190             {
191                 using (var stringWriter = new StringWriter())
192                 {
193                     using (XmlWriter writer = XmlWriter.Create(stringWriter))
194                     {
195                         xmlSerializer.Serialize(writer, obj);
196                         return XElement.Parse(stringWriter.ToString()); // Your XML
197                     }
198                 }
199             }
200         }
201 
202         /// <summary>
203         /// 将xml元素转成C#类型对象
204         /// </summary>
205         /// <typeparam name="T"></typeparam>
206         /// <param name="xElement"></param>
207         /// <returns></returns>
208         public static T FromXElement<T>(XElement xElement)
209         {
210             var xmlSerializer = new XmlSerializer(typeof(T));
211             return (T)xmlSerializer.Deserialize(xElement.CreateReader());
212         }
213 
214         /// <summary>
215         /// 读取所有指定名称的XML元素里面的所有内容,并返回它的C#类型的对象集合信息
216         /// </summary>
217         /// <typeparam name="T"></typeparam>
218         /// <param name="reader"></param>
219         /// <param name="elementName"></param>
220         /// <returns></returns>
221         public static List<T> GetAllObjectByXMLElement<T>(XmlReader reader, string elementName)
222         {
223             List<T> list = null;
224             if (reader != null)
225             {
226                 list = new List<T>();
227                 reader.MoveToContent();
228                 // Parse the file and display each of the nodes.
229                 while (reader.Read())
230                 {
231                     switch (reader.NodeType)
232                     {
233                         case XmlNodeType.Element:
234                             if (string.Equals(elementName, reader.Name))
235                             {
236                                 XElement xElement = XElement.ReadFrom(reader) as XElement;
237                                 if (xElement != null)
238                                 {
239                                     list.Add(FromXElement<T>(xElement));
240                                 }
241                             }
242                             break;
243                     }
244                 }
245                 list.TrimExcess();
246             }
247             return list ?? new List<T>(0);
248         }
249         /// <summary>
250         /// 将每一个指定名称的XML元素转成C#类型的对象,然后在执行Action方法做进一步的业务处理,目的是为了解决批量处理全部指定名称的XML元素内容转成C#对象集合后内存溢出的问题。 (将每一个指定名称XML元素逐个转成C#类型的对象,然后在逐个处理这个C#类型的对象)
251         /// </summary>
252         /// <typeparam name="T"></typeparam>
253         /// <param name="reader"></param>
254         /// <param name="elementName"></param>
255         /// <param name="action"></param>
256         public static void EachOfXmlElementConvertObjectHandler<T>(XmlReader reader, string elementName, Action<T> action)
257         {
258             if (reader != null)
259             {
260                 reader.MoveToContent();
261                 // Parse the file and display each of the nodes.
262                 while (reader.Read())
263                 {
264                     switch (reader.NodeType)
265                     {
266                         case XmlNodeType.Element:
267                             if (string.Equals(elementName, reader.Name))
268                             {
269                                 XElement xElement = XElement.ReadFrom(reader) as XElement;
270                                 if (xElement != null)
271                                 {
272                                     action(FromXElement<T>(xElement));
273                                 }
274                             }
275                             break;
276                     }
277                 }
278             }
279         }
280         /// <summary>
281         /// 将每一个指定名称的XML元素转成C#类型的对象,然后在执行Func方法做进一步的业务处理,目的是为了解决批量处理全部指定名称的XML元素内容转成C#对象集合后内存溢出的问题。 (将每一个指定名称XML元素逐个转成C#类型的对象,然后在逐个处理这个C#类型的对象)
282         /// </summary>
283         /// <typeparam name="T"></typeparam>
284         /// <param name="reader"></param>
285         /// <param name="elementName"></param>
286         /// <param name="func">返回false退出循环,不在继续执行</param>
287         public static void EachOfXmlElementConvertObjectHandler<T>(XmlReader reader, string elementName, Func<T, bool> func)
288         {
289             if (reader != null)
290             {
291                 reader.MoveToContent();
292                 // Parse the file and display each of the nodes.
293                 while (reader.Read())
294                 {
295                     switch (reader.NodeType)
296                     {
297                         case XmlNodeType.Element:
298                             if (string.Equals(elementName, reader.Name))
299                             {
300                                 XElement xElement = XElement.ReadFrom(reader) as XElement;
301                                 if (xElement != null)
302                                 {
303                                     if (!func(FromXElement<T>(xElement)))
304                                     {
305                                         return;
306                                     }
307                                 }
308                             }
309                             break;
310                     }
311                 }
312             }
313         }
314     }
315 }
XmlHelper.cs
复制代码

 

 

posted @   —八戒—  阅读(281)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示