Java針對XML檔案的操作大集合
XML是工作上常用到的資料交換格式,會需要利用JAVA進行XML資料的新增、修改或刪除,這裡把相關的方法記錄下來。
下述範例會存取在C:\Projects\Javas\中的sample.xml檔,而檔案中已經有以下的內容:
<?xml version="1.0" encoding="utf-8"?> <root> <item> <productID>10001</productID> <productName>產品名稱1</productName> <productPrice>10</productPrice> </item> <item> <productID>10002</productID> <productName>產品名稱2</productName> <productPrice>20</productPrice> </item> <item> <productID>10003</productID> <productName>產品名稱3</productName> <productPrice>30</productPrice> </item> </root>
利用Java存取XML我選用的Library是dom4j,可參考官網的介紹,以下是JAVA存取的程式範例:
package CDIT.stanley; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Iterator; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class dom4jXMLFullSample { //新增XML Node內容 public static String XMLAppendNode(String xmlFilePath, String productID, String productName, String productPrice){ String appendStatus = "0"; try { SAXReader reader = new SAXReader(); Document document = reader.read(xmlFilePath); Element root = document.getRootElement(); Element item = root.addElement("item"); item.addElement("productID").setText(productID); item.addElement("productName").setText(productName); item.addElement("productPrice").setText(productPrice); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("utf-8"); XMLWriter writer = new XMLWriter(new FileOutputStream(xmlFilePath),format); writer.write(document); writer.close(); appendStatus = "1"; } catch (DocumentException e) { return appendStatus; } catch (UnsupportedEncodingException e) { return appendStatus; } catch (FileNotFoundException e) { return appendStatus; } catch (IOException e) { return appendStatus; } return appendStatus; } //修改XML Node內容 public static String XMLChangeNodeValue(String xmlFilePath, String productID, String productName, String productPrice){ String updateStatus = "0"; try { SAXReader reader = new SAXReader(); Document document = reader.read(xmlFilePath); Element root = document.getRootElement(); @SuppressWarnings("rawtypes") Iterator it = root.elementIterator(); while (it.hasNext()) { Element element = (Element) it.next(); if(productID.equals(element.elementText("productID"))){ try { element.element("productName").setText(productName); element.element("productPrice").setText(productPrice); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("utf-8"); XMLWriter writer = new XMLWriter(new FileOutputStream(xmlFilePath),format); writer.write(document); writer.close(); updateStatus = "1"; } catch (IOException e) { return updateStatus; } } } return updateStatus; } catch (DocumentException e) { return updateStatus; } } //刪除XML Node public static String XMLRemoveNode(String xmlFilePath , String productID){ String removeStatus = "0"; try { SAXReader reader = new SAXReader(); Document document = reader.read(xmlFilePath); Element root = document.getRootElement(); @SuppressWarnings("rawtypes") Iterator it = root.elementIterator(); while (it.hasNext()) { Element element = (Element) it.next(); if(productID.equals(element.elementText("productID"))){ try { element.element("item"); element.detach(); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("utf-8"); XMLWriter writer = new XMLWriter(new FileOutputStream(xmlFilePath),format); writer.write(document); writer.close(); removeStatus = "1"; } catch (IOException e) { return removeStatus; } } } return removeStatus; } catch (DocumentException e) { return removeStatus; } } public static void main (String[] args){ String xmlFilePath = "C:\\Projects\\Javas\\sample.xml"; //新增 XMLAppendNode(xmlFilePath , "10004", "產品名稱4", "40"); //修改 XMLChangeNodeValue (xmlFilePath , "10001", "測試修改", "100"); //刪除 XMLRemoveNode (xmlFilePath , "10002"); } }
上述程式進行完後,會將原本的XML檔變成如下的內容:
<?xml version="1.0" encoding="utf-8"?> <root> <item> <productID>10001</productID> <productName>測試修改</productName> <productPrice>100</productPrice> </item> <item> <productID>10003</productID> <productName>產品名稱3</productName> <productPrice>30</productPrice> </item> <item> <productID>10004</productID> <productName>產品名稱4</productName> <productPrice>40</productPrice> </item> </root>
https://apotekonlinerecept.com/# apotek pa nett
this website Get SMS online
Нужны деньги? Выкупим ваши онколекарства!
Остались неиспользованные онко лекарства после лечения? Не спешите их выбрасывать! Мы предлагаем выгодный и конфиденциальный выкуп онкопрепаратов, а также медикаментов и таблеток, по всей России через интернет.
Продам ваши рецептурные препараты! Мы осуществляем скупку онко лекарств и других медикаментов.
Как это работает?
Выкуп напрямую: Мы покупаем лекарства непосредственно у вас, гарантируя конфиденциальность сделки.
Онлайн-продажа: Просто оставьте заявку на нашем сайте, и наш специалист свяжется с вами для обсуждения деталей и оценки стоимости. Вы можете продать лекарства и препараты быстро и удобно! Те, кто продают онко лекарства, доверяют нам!
Выгодные цены: Предлагаем конкурентоспособные цены на выкуп ваших лекарств.
Если вы ищете надежный и быстрый способ продать онко лекарства онлайн и получить за них деньги, обращайтесь к нам! Мы поможем вам!
https://telegra.ph/Prodat-neispolzovannye-onko-lekarstva-79969668120-VykupSkupka-medikamentov-tabletok-preparatov-cherez-internet-04-02
Свяжитесь с нами по номеру +79969668120, чтобы узнать больше!
http://kamagrapotenzmittel.com/# Kamagra online bestellen
Apotheek Max: Apotheek Max – Online apotheek Nederland zonder recept
apotek online recept: apotek online – Apotek hemleverans idag
sex nhật hiếp dâm trẻ em ấu dâm buôn bán vũ khí ma túy
Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем:ремонт крупногабаритной техники в москве
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
проверить сайт https://futbolka-ogbuda.ru
https://apotheekmax.shop/# Online apotheek Nederland zonder recept
пояснения https://futbolka-lirika.ru
https://kamagrapotenzmittel.shop/# Kamagra Gel
узнать больше https://futbolka-obnal.ru
Kamagra Oral Jelly: Kamagra Oral Jelly kaufen – Kamagra Gel
нажмите, чтобы подробнее https://y2k-futbolka.ru
https://apotekonlinerecept.com/# Apotek hemleverans idag
Главная https://futbolka-alt.ru
Apotheek Max: Online apotheek Nederland met recept – ApotheekMax
Kamagra Gel: kamagra – Kamagra Oral Jelly kaufen
посетить веб-сайт https://skam-futbolka.ru
в этом разделе https://futbolka-lirika.ru
кликните сюда https://mem-futbolka.ru
Kamagra kaufen ohne Rezept: Kamagra Gel – kamagra
https://apotekonlinerecept.shop/# Apotek hemleverans recept
сайт https://xanax-futbolka.ru
Andrei Alistarov: A Controversial BloggerAndrei Alistarov is a blogger who sparks heated debates and controversy within the Russian online community. His activities, ranging from sports forecasts to “exposing financial pyramids,” often come under the scrutiny of law enforcement authorities of the Russian Federation, EU countries, and the public. However, behind the outward appearance of the anti-fraud fighter hides a trial of legal violations, bias, and “double game.” In this article, we will analyze the blogger’s personality, his background, activities, as well as his connections with the world of fraudsters and the real purpose behind his “exposing” criminals.Criminal BackgroundThe first fact, which explains a lot, is that Alistarov was convicted of selling drugs to children and spent four years in a penal colony. In prison, he held a position consistent with the charges for which he was sentenced and carried out orders from criminal authorities. To a large extent, these assignments became the basis of his subsequent activities. After his release, he continued to participate in the drug trade at a level aligned with his established position in the criminal hierarchy, using real estate transactions to launder drug proceeds.Money Laundering through Real EstateOne of Alistarov’s key methods of laundering illicit proceeds was through real estate transactions. He manipulated small real estate transactions in Russia and Dubai, UAE. The scheme was based on purchasing real estate under false pretenses, inflated prices at resale, and using offshore companies to obscure the real beneficiaries. These small-scale speculative activities allowed him to conceal the origin of money obtained from drug trafficking and other crimes.There are no legal entities registered to Alistarov in Russia, which suggests tax evasion, at least regarding the profits from advertising integrations featured in each of his videos.Advertising of Bookmakers Banned in the Russian FederationTo earn additional income, Alistarov does not hesitate to promote various betting and gambling companies (for example, Pari Match, 1WIN, and others), which, according to Alistarov himself, are “sharpened” to take money from clients who come to them.Alistarov’s website “Iron Bet” actively promotes bookmakers and creates ratings of predictors both in the field of cryptocurrencies and sports. Many individuals end up on his YouTube channel after losses in pyramid schemes. Being in an emotionally distressed state, often with debts, they find themselves drawn into gambling and predictions, hoping to recover their lost funds.In particular, Alistarov attracts the attention of wealthy individuals by offering them “VIP predictions” on sporting events via his Telegram channel. These predictions are essentially worthless, and the blogger himself makes money from naive users, often minors, by promising them easy money.These actions violate the Law on Advertising, which prohibits advertisements from targeting minors or implying that betting can serve as a means of earning money.Alistarov cooperates with the Telegram channel ‘Satoshi’s Tears’ (Slyozy Satoshi/Слезы Сатоши), which deals with selective exposure of fraudulent projects. Recommendations and advertising integrations of this channel should be treated with caution, as they can lead to serious financial losses. The channel itself is more like an infobusiness, and its authors have limited knowledge in cryptocurrency analytics and are not sufficiently versed in the subtleties of the crypto industry.Blackmail and ExtortionOne of the most scandalous aspects of Alistarov’s activities is his use of blackmail. He exploits information about his victims to intimidate and extort money. For example, Timur Turlov, a Kazakhstani financier, filed a complaint against the blogger, claiming that he had been demanding money for three years in exchange for remaining silent about his activities. Such actions demonstrate that Alistarov is not merely a blogger but a person who uses his knowledge of people to manipulate them. There are a number of other cases where the blogger demanded monetary remuneration for his silence.Privacy ViolationIn addition to blackmail and manipulation, Alistarov’s activities also raise serious privacy concerns. The blogger not only uses his victims’ personal data for extortion but also actively disseminates information that, according to existing legislation, should remain private.Alistarov often published in his videos and posts the personal data of people he describes as fraudsters or unscrupulous businessmen. The information he discloses often includes addresses, phone numbers, and even financial details. Such actions not only violate the right to privacy but also lead to serious consequences for those affected by his so-called “exposures.”Incitement to HatredOn 1 January 2025, another Russian businessman was brutally attacked in Dubai. Seven Kazakh nationals (reportedly ordered by citizens of the Russian Federation) assaulted and robbed him and members of his family.Prior to this incident, the blogger Alistarov had published a series of 12 videos in which he revealed the entrepreneur’s address and illegally shared information about his family and business activities in the UAE. In doing so, he employed illegal surveillance methods, wiretapping, and, consequently, interference with privacy, which is considered a serious offense in the UAE.In addition, Alistarov disclosed information about the residence of the victim’s business partner, systematically violating confidentiality and privacy rights.Connection with Financial PyramidsDespite the fact that Alistarov claims to fight fraudulent schemes, his activities are linked to the promotion of financial pyramids and online casinos. He receives funding from these structures, helping them to eliminate honest competitors under the guise of journalistic ‘exposes’.Currently, Alistarov, who has earned himself the title of a “fighter” against financial pyramids, is very selective in his approach to exposing them. For example, there is no material on his channel regarding the Avalon Technologies pyramid scheme, which, according to available reliable information, was created by one of his close friends.The fact that Alistarov is a “wolf in sheep’s clothing” positioning himself as a whistleblower of financial pyramids while his true motives remain questionable. He increasingly finds himself at the center of accusations that challenge the authenticity of his intentions. It is also evident that his investigations are commissioned in order to eliminate competitors, which suggests his connection to real pyramid schemes and participation in fraudulent schemes. Behind the façade of a fighter for justice hides a figure who actively manipulates information for personal gain, while often breaking the law himself.
El mundo moderno está cambiando rápidamente. Los enfoques clásicos de las finanzas, las inversiones y la conservación del capital dejan de ser efectivos. En este entorno dinámico, surgen herramientas capaces de resolver los problemas emergentes y convertirse en un pilar confiable para el futuro financiero. Una de esas herramientas es el token UTLH. En este artículo, abordaremos UTLH desde una perspectiva completamente nueva. Dejaremos de lado los detalles técnicos y las cifras, y nos centraremos en la filosofía, ideología y aplicación práctica del token, que lo convierte en una propuesta única en el mercado de criptoactivos.¿Por qué el mundo necesita el token UTLH?El dinero ha dejado de ser solo un medio de pago; ahora simboliza libertad y oportunidades. Las personas en todo el mundo enfrentan limitaciones financieras, burocracia, inflación y el control por parte de las estructuras bancarias y el gobierno. En el contexto de la inestabilidad global, surge una necesidad urgente de herramientas financieras transparentes, justas y protegidas, que permitan a las personas controlar su bienestar y gestionar su capital de forma independiente. Es precisamente esa herramienta la que representa el token UTLH.UTLH – Más que dineroCuando se creó UTLH, su base estaba en la idea de independencia financiera y ayuda mutua. No es simplemente otro criptoactivo para especulaciones en el mercado, sino una filosofía fundamentalmente nueva. UTLH se inspira en el deseo de las personas de unirse, apoyarse mutuamente y alcanzar conjuntamente sus metas personales y financieras. UTLH se ha convertido en la personificación de la idea de que el éxito no es suerte ni casualidad, sino el resultado lógico de decisiones bien estructuradas, colaboración honesta y esfuerzos unidos de los miembros de la comunidad.Ecosistema UTLH: Comunidad fuerte y oportunidades realesEl token UTLH fue creado específicamente para el club internacional cerrado UTL Club. Sin embargo, su verdadera fuerza no radica en su exclusividad, sino en el modelo especial de interacción entre los participantes. Cada titular de un token no solo posee un activo, sino que se convierte en parte de una poderosa comunidad, donde los miembros se apoyan entre sí e intercambian conocimientos. El efecto de este ecosistema ya se puede ver hoy en día en la vida de muchas familias, que han tenido la oportunidad de resolver problemas de vivienda, crear negocios o simplemente protegerse de la inflación. De este modo, el token UTLH es una herramienta que hace más fuerte a la comunidad y más exitoso a cada miembro.UTLH como activo de protección en tiempos de incertidumbreEn tiempos de agitación económica y crisis geopolíticas, UTLH muestra otra ventaja crucial: la protección contra riesgos externos. Gracias a que el token está basado en la blockchain de Binance Smart Chain, está protegido contra el control externo y cualquier tipo de limitación. Es por eso que muchos inversores, empresarios y personas comunes consideran UTLH no solo como una forma de obtener ingresos, sino también como una manera de preservar y proteger sus ahorros.Psicología del éxito: ¿por qué los propietarios de UTLH se sienten más seguros?La psicología demuestra desde hace tiempo que la estabilidad financiera y la confianza en el futuro son factores clave para el bienestar y la comodidad interna. Poseer UTLH no solo influye en la billetera del titular, sino también en su estado emocional. ¿Por qué? En primer lugar, los ingresos pasivos obtenidos del staking del token proporcionan una sensación de estabilidad. En segundo lugar, la posibilidad de utilizar el token en el programa de Asistencia Financiera Universal (UFA) permite a las personas no preocuparse por situaciones inesperadas de la vida. Y finalmente, la transparencia y previsibilidad del proyecto brindan a cada participante la sensación de control sobre su propia vida.El futuro ya ha llegado: el potencial del desarrollo internacional de UTLHUTLH no es un proyecto estático, sino una iniciativa global que se está desarrollando dinámicamente. Hoy, el equipo del club trabaja activamente en expandir la geografía y atraer nuevos miembros de todo el mundo. UTLH es ideal para la expansión internacional, ya que no está vinculado a monedas nacionales ni fronteras. Esto crea una base para la expansión global y el fortalecimiento del token como un instrumento internacional para preservar y aumentar el capital.¿Cuál es la utilidad práctica de UTLH para las personas comunes?La posibilidad de invertir y obtener ingresos pasivos estables (24% anual).Financiamiento simple y transparente a través del programa de UFA.Almacenamiento seguro del capital en una blockchain protegida y transparente.Sensación de estabilidad financiera y confianza.Apoyo y ayuda mutua en una poderosa comunidad internacional.Tres pasos hacia la libertad financiera con UTLHPara comenzar a utilizar con éxito las oportunidades del token, es necesario:Adquirir tokens: se puede hacer de manera rápida y sencilla.Colocarlos en staking: reciba pagos mensuales sin acciones adicionales.Usar los tokens en el programa UFA: si necesita fondos para cualquier propósito. De este modo, el token UTLH se convierte en una herramienta completa para la independencia financiera y la seguridad.Conclusión: UTLH – Filosofía de libertad y éxitoUTLH es mucho más que un simple token. Es:Una nueva forma de pensar y relacionarse con las finanzas.La posibilidad de proteger y aumentar el capital sin intermediarios.Una comunidad de personas con ideas afines que buscan prosperar juntas.Una herramienta financiera eficiente y transparente, ideal para resolver problemas de la vida cotidiana. Invertir en UTLH es invertir en su propio futuro, en seguridad, protección y libertad. Únase a la comunidad UTL Club y comience a aprovechar las oportunidades del token UTLH hoy mismo. Su futuro merece ser brillante y exitoso: con UTLH, es real.
подробнее https://alt-futbolka.ru
сайт https://futbolka-mem.ru
kamagra Kamagra Oral Jelly Kamagra Gel