minidom-0.18.0/.cargo_vcs_info.json0000644000000001450000000000100125560ustar { "git": { "sha1": "30b049a7d44ada6960dc99fd14d17e4c628d8f14" }, "path_in_vcs": "minidom" }minidom-0.18.0/CHANGELOG.md000064400000000000000000000123101046102023000131540ustar 00000000000000Version NEXT: Version 0.18, released 2025-10-28: * Breaking: * Remove 'std' feature for now because it makes build fail on no-default-features. * Add `Element::attr_ns` that requires the attribute namespace in addition to `Element::attr` (which defaults to `rxml::Namespace::none()`. Similar changes on `ElementBuilder` methods. `Element` now uses `AttrMap` to store attributes, and this also implies some more changes in the Element interface such as iterators on attributes. * Changes * Use thiserror for the error type. (!616) Version 0.17, released 2025-09-17: * Changes * Almost make the whole crate `no_std`, only `std::io` is still remaining. * Update rxml dependency to 0.13. * Fixes * Remove warnings for elided lifetimes (rustc 1.90) * Fixes serialization and ensure prefixes are set on Element when using `Element::from_reader_with_prefixes`. Version 0.16, released 2024-07-23: * Breaking * Element comparison returns unequal when number of nodes is unequal. * Changes * New `Element::append_text` method. * Update rxml to 0.11.0 * Fixes * Prevent splitting of text nodes in TreeBuilder when there is no element in between. * Update to edition 2021. * Fix clippy lints, and other compiler warnings. Version 0.15.2, released 2023-05-13: * Changes * Fix a memory corruption on closing tags for elements with a name longer than 24 bytes * Only enable the mt features of rxml, we don’t need any additional one Version 0.15.1, released 2023-01-15: * Changes * Add `Element::from_reader_with_prefixes` * (#44) Add test ensuring parsing two namespaces resolv Version 0.15.0, released 2022-07-13: * Changes * Drop quick-xml dependency (astro1, jssfr) Version 0.14.0, released 2022-03-07: * Changes * Bump quick-xml dependency (thanks eijebong!) * Fixes * Handle identical namespaces of sibling elements correctly (thanks Jasper!) * Fix support for newer rustc (see https://github.com/rust-lang/rust/issues/90199) Version 0.13.0, released 2021-01-13: * Changes * Force namespaces on Element, which was a breaking change. Version 0.12.1, released 2021-01-13, yanked: * Changes * Bump quick-xml dependency. Version 0.12, released 2020-02-15: * Breaking * `Element.write_to` doesn't prepand xml prelude anymore. Use `write_to_decl` when necessary. * PartialEq implementation for Element and Node have been changed to ensure namespaces match even if the objects are not structurally equivalent in Rust. * Changes * Explicitely focus on XMPP. Some features will eventually be removed from the project to comply with this. * Update edition to 2018 * Add NSChoice enum to allow comparing NSs differently * Add impl for From> for Node * Fixes * Update old CI configuration with newer Rust images Version 0.11.1, released 2019-09-06: * Changes * Update to quick-xml 0.16 * Add a default "comments" feature to transform comments into errors when unset. Version 0.11.0, released 2019-06-14: * Breaking * Get rid of IntoElements, replace with `Into` and ` IntoIterator>` * Fixes * Remote unused `mut` attribute on variable * Changes * Update quick-xml to 0.14 * Split Node into its own module * Nicer Debug implementation for NamespaceSet Version 0.10.0, released 2018-10-21: * Changes * Update quick-xml to 0.13 * Update doc to reflect switch from xml-rs to quick-xml. Version 0.9.1, released 2018-05-29: * Fixes * Lumi fixed CDATA handling, minidom will not unescape CDATA bodies anymore. * Small changes - Link Mauve implemented IntoAttributeValue on std::net::IpAddr. Version 0.9.0, released 2018-04-10: * Small changes - Upgrade quick_xml to 0.12.1 Version 0.8.0, released 2018-02-18: * Additions - Link Mauve replaced error\_chain with failure ( https://gitlab.com/lumi/minidom-rs/merge_requests/27 ) - Yue Liu added support for writing comments and made the writing methods use quick-xml's EventWriter ( https://gitlab.com/lumi/minidom-rs/merge_requests/26 ) Version 0.6.2, released 2017-08-27: * Additions - Link Mauve added an implementation of IntoElements for all Into ( https://gitlab.com/lumi/minidom-rs/merge_requests/19 ) Version 0.6.1, released 2017-08-20: * Additions - Astro added Element::has_ns, which checks whether an element's namespace matches the passed argument. ( https://gitlab.com/lumi/minidom-rs/merge_requests/16 ) - Link Mauve updated the quick-xml dependency to the latest version. * Fixes - Because break value is now stable, Link Mauve rewrote some code marked FIXME to use it. Version 0.6.0, released 2017-08-13: * Big changes - Astro added proper support for namespace prefixes. ( https://gitlab.com/lumi/minidom-rs/merge_requests/14 ) * Fixes - Astro fixed a regression that caused the writer not to escape its xml output properly. ( https://gitlab.com/lumi/minidom-rs/merge_requests/15 ) Version 0.5.0, released 2017-06-10: * Big changes - Eijebong made parsing a lot faster by switching the crate from xml-rs to quick_xml. ( https://gitlab.com/lumi/minidom-rs/merge_requests/11 ) minidom-0.18.0/Cargo.lock0000644000000101450000000000100105320ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "bytes" version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a" [[package]] name = "castaway" version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" dependencies = [ "rustversion", ] [[package]] name = "cfg-if" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "compact_str" version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f86b9c4c00838774a6d902ef931eff7470720c51d90c2e32cfe15dc304737b3f" dependencies = [ "castaway", "cfg-if", "itoa", "ryu", "static_assertions", ] [[package]] name = "futures-core" version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" [[package]] name = "itoa" version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] name = "minidom" version = "0.18.0" dependencies = [ "rxml", "thiserror", ] [[package]] name = "proc-macro2" version = "1.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e0f6df8eaa422d97d72edcd152e1451618fed47fabbdbd5a8864167b1d4aff7" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.41" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce25767e7b499d1b604768e7cde645d14cc8584231ea6b295e9c9eb22c02e1d1" dependencies = [ "proc-macro2", ] [[package]] name = "rustversion" version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" [[package]] name = "rxml" version = "0.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f288457ad3607c08953ca5604229ebb03878a0b4491d8f545d547281c2b3e0c5" dependencies = [ "bytes", "futures-core", "rxml_proc", "rxml_validation", ] [[package]] name = "rxml_proc" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d46a2e263a1beb8b39e69bffee9f2395f479cc02472c247af00e065006970ca7" dependencies = [ "quote", "rxml_validation", "syn", ] [[package]] name = "rxml_validation" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "826e80413b9a35e9d33217b3dcac04cf95f6559d15944b93887a08be5496c4a4" dependencies = [ "compact_str", ] [[package]] name = "ryu" version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" [[package]] name = "static_assertions" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "syn" version = "2.0.108" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da58917d35242480a05c2897064da0a80589a2a0476c9a3f2fdc83b53502e917" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "thiserror" version = "2.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" version = "2.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "unicode-ident" version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "462eeb75aeb73aea900253ce739c8e18a67423fadf006037cd3ff27e82748a06" minidom-0.18.0/Cargo.toml0000644000000031320000000000100105530ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "minidom" version = "0.18.0" authors = [ "lumi ", "Emmanuel Gil Peyrot ", "Bastien Orivel ", "Astro ", "Maxime “pep” Buquet ", ] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "A small, simple DOM implementation on top of rxml, targeting the subset of XML useful for XMPP" homepage = "https://gitlab.com/xmpp-rs/xmpp-rs" documentation = "https://docs.rs/minidom" readme = "README.md" keywords = [ "xml", "xmpp", ] license = "MPL-2.0" repository = "https://gitlab.com/xmpp-rs/xmpp-rs" [badges.gitlab] repository = "xmpp-rs/xmpp-rs" [lib] name = "minidom" path = "src/lib.rs" [[example]] name = "articles" path = "examples/articles.rs" [dependencies.rxml] version = "0.13.1" features = [ "std", "compact_str", ] default-features = false [dependencies.thiserror] version = "2.0" [dev-dependencies.rxml] version = "0.13.1" features = [ "std", "compact_str", "macros", ] default-features = false minidom-0.18.0/Cargo.toml.orig000064400000000000000000000016071046102023000142410ustar 00000000000000[package] name = "minidom" version = "0.18.0" authors = [ "lumi ", "Emmanuel Gil Peyrot ", "Bastien Orivel ", "Astro ", "Maxime “pep” Buquet ", ] description = "A small, simple DOM implementation on top of rxml, targeting the subset of XML useful for XMPP" homepage = "https://gitlab.com/xmpp-rs/xmpp-rs" repository = "https://gitlab.com/xmpp-rs/xmpp-rs" documentation = "https://docs.rs/minidom" readme = "README.md" keywords = ["xml", "xmpp"] license = "MPL-2.0" edition = "2021" [badges] gitlab = { repository = "xmpp-rs/xmpp-rs" } [dependencies] rxml = { version = "0.13.1", default-features = false, features = [ "std", "compact_str" ] } thiserror = "2.0" [dev-dependencies] rxml = { version = "0.13.1", default-features = false, features = [ "std", "compact_str", "macros" ] } minidom-0.18.0/LICENSE000064400000000000000000000405261046102023000123620ustar 00000000000000Mozilla Public License Version 2.0 ================================== 1. Definitions -------------- 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 1.3. "Contribution" means Covered Software of a particular Contributor. 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. "Incompatible With Secondary Licenses" means (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. "Executable Form" means any form of the work other than Source Code Form. 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" means this document. 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. "Modifications" means any of the following: (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or (b) any new file in Source Code Form that contains any Covered Software. 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. "Source Code Form" means the form of the work preferred for making modifications. 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions -------------------------------- 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: (a) for any code that a Contributor has removed from Covered Software; or (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities ------------------- 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation --------------------------------------------------- If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination -------------- 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. ************************************************************************ * * * 6. Disclaimer of Warranty * * ------------------------- * * * * Covered Software is provided under this License on an "as is" * * basis, without warranty of any kind, either expressed, implied, or * * statutory, including, without limitation, warranties that the * * Covered Software is free of defects, merchantable, fit for a * * particular purpose or non-infringing. The entire risk as to the * * quality and performance of the Covered Software is with You. * * Should any Covered Software prove defective in any respect, You * * (not any Contributor) assume the cost of any necessary servicing, * * repair, or correction. This disclaimer of warranty constitutes an * * essential part of this License. No use of any Covered Software is * * authorized under this License except under this disclaimer. * * * ************************************************************************ ************************************************************************ * * * 7. Limitation of Liability * * -------------------------- * * * * Under no circumstances and under no legal theory, whether tort * * (including negligence), contract, or otherwise, shall any * * Contributor, or anyone who distributes Covered Software as * * permitted above, be liable to You for any direct, indirect, * * special, incidental, or consequential damages of any character * * including, without limitation, damages for lost profits, loss of * * goodwill, work stoppage, computer failure or malfunction, or any * * and all other commercial damages or losses, even if such party * * shall have been informed of the possibility of such damages. This * * limitation of liability shall not apply to liability for death or * * personal injury resulting from such party's negligence to the * * extent applicable law prohibits such limitation. Some * * jurisdictions do not allow the exclusion or limitation of * * incidental or consequential damages, so this exclusion and * * limitation may not apply to You. * * * ************************************************************************ 8. Litigation ------------- Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 9. Miscellaneous ---------------- This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License --------------------------- 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice ------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - "Incompatible With Secondary Licenses" Notice --------------------------------------------------------- This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. minidom-0.18.0/README.md000064400000000000000000000004141046102023000126240ustar 00000000000000minidom ======= What's this? ------------ A minimal DOM library on top of rxml, targeting exclusively the subset of XML useful for XMPP. | Restriction | Supported ✅ | Unsupported ❌ | | - | - | - | | Namespaces are mandatory | `` | `` | minidom-0.18.0/examples/articles.rs000064400000000000000000000025021046102023000153370ustar 00000000000000// Copyright (c) 2020 lumi // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. extern crate minidom; use minidom::Element; const DATA: &str = r#"
10 Terrible Bugs You Would NEVER Believe Happened Rust fixed them all. <3
BREAKING NEWS: Physical Bug Jumps Out Of Programmer's Screen Just kidding!
"#; const ARTICLE_NS: &str = "article"; #[derive(Debug)] pub struct Article { pub title: String, pub body: String, } fn main() { let root: Element = DATA.parse().unwrap(); let mut articles: Vec
= Vec::new(); for child in root.children() { if child.is("article", ARTICLE_NS) { let title = child.get_child("title", ARTICLE_NS).unwrap().text(); let body = child.get_child("body", ARTICLE_NS).unwrap().text(); articles.push(Article { title: title, body: body.trim().to_owned(), }); } } println!("{:?}", articles); } minidom-0.18.0/src/convert.rs000064400000000000000000000051011046102023000141600ustar 00000000000000// Copyright (c) 2020 lumi // Copyright (c) 2020 Emmanuel Gil Peyrot // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //! A module which exports a few traits for converting types to elements and attributes. use alloc::string::String; /// A trait for types which can be converted to an attribute value. pub trait IntoAttributeValue { /// Turns this into an attribute string, or None if it shouldn't be added. fn into_attribute_value(self) -> Option; } macro_rules! impl_into_attribute_value { ($t:ty) => { impl IntoAttributeValue for $t { fn into_attribute_value(self) -> Option { Some(self.to_string()) } } }; } macro_rules! impl_into_attribute_values { ($($t:ty),*) => { $(impl_into_attribute_value!($t);)* } } impl_into_attribute_values!( usize, u64, u32, u16, u8, isize, i64, i32, i16, i8, ::core::net::IpAddr ); impl IntoAttributeValue for String { fn into_attribute_value(self) -> Option { Some(self) } } impl IntoAttributeValue for &String { fn into_attribute_value(self) -> Option { Some(self.to_owned()) } } impl IntoAttributeValue for &str { fn into_attribute_value(self) -> Option { Some(self.to_owned()) } } impl IntoAttributeValue for Option { fn into_attribute_value(self) -> Option { self.and_then(IntoAttributeValue::into_attribute_value) } } #[cfg(test)] mod tests { use super::IntoAttributeValue; use core::net::IpAddr; use core::str::FromStr; #[test] fn test_into_attribute_value_on_ints() { assert_eq!(16u8.into_attribute_value().unwrap(), "16"); assert_eq!(17u16.into_attribute_value().unwrap(), "17"); assert_eq!(18u32.into_attribute_value().unwrap(), "18"); assert_eq!(19u64.into_attribute_value().unwrap(), "19"); assert_eq!(16i8.into_attribute_value().unwrap(), "16"); assert_eq!((-17i16).into_attribute_value().unwrap(), "-17"); assert_eq!(18i32.into_attribute_value().unwrap(), "18"); assert_eq!((-19i64).into_attribute_value().unwrap(), "-19"); assert_eq!( IpAddr::from_str("0000:0::1") .unwrap() .into_attribute_value() .unwrap(), "::1" ); } } minidom-0.18.0/src/element.rs000064400000000000000000001032141046102023000141350ustar 00000000000000// Copyright (c) 2020 lumi // Copyright (c) 2020 Emmanuel Gil Peyrot // Copyright (c) 2020 Bastien Orivel // Copyright (c) 2020 Maxime “pep” Buquet // Copyright (c) 2020 Yue Liu // Copyright (c) 2020 Matt Bilker // Copyright (c) 2020 Xidorn Quan // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //! Provides an `Element` type, which represents DOM nodes, and a builder to create them with. use crate::convert::IntoAttributeValue; use crate::error::{Error, Result}; use crate::namespaces::NSChoice; use crate::node::Node; use crate::prefixes::{Namespace, Prefix, Prefixes}; use crate::tree_builder::TreeBuilder; use alloc::borrow::Cow; use alloc::string::String; use alloc::vec::Vec; use core::slice; use core::str::FromStr; use std::borrow::Borrow; use std::hash::Hash; use std::io; use rxml::writer::{Encoder, Item, TrackNamespace}; use rxml::{AttrMap, Namespace as RxmlNamespace, NcName, RawReader, XmlVersion}; fn encode_and_write( item: Item<'_>, enc: &mut Encoder, mut w: W, ) -> io::Result<()> { let mut buf = rxml::bytes::BytesMut::new(); enc.encode_into_bytes(item, &mut buf) .expect("encoder driven incorrectly"); w.write_all(&buf[..])?; Ok(()) } /// Wrapper around a [`io::Write`] and an [`rxml::writer::Encoder`], to /// provide a simple function to write an rxml Item to a writer. pub struct CustomItemWriter { writer: W, encoder: Encoder, } impl CustomItemWriter { pub(crate) fn new(writer: W) -> Self { Self { writer, encoder: Encoder::new(), } } } impl CustomItemWriter { pub(crate) fn write(&mut self, item: Item<'_>) -> io::Result<()> { encode_and_write(item, &mut self.encoder, &mut self.writer) } } /// Type alias to simplify the use for the default namespace tracking /// implementation. pub type ItemWriter = CustomItemWriter; /// helper function to escape a `&[u8]` and replace all /// xml special characters (<, >, &, ', ") with their corresponding /// xml escaped value. #[must_use] pub fn escape(raw: &[u8]) -> Cow<'_, [u8]> { fn to_escape(b: u8) -> bool { matches!(b, b'<' | b'>' | b'\'' | b'&' | b'"') } let mut escapes: Vec<(usize, &'static [u8])> = Vec::new(); let mut bytes = raw.iter(); let mut loc = 0; while let Some(i) = bytes.position(|&b| to_escape(b)) { loc += i; match raw[loc] { b'<' => escapes.push((loc, b"<")), b'>' => escapes.push((loc, b">")), b'\'' => escapes.push((loc, b"'")), b'&' => escapes.push((loc, b"&")), b'"' => escapes.push((loc, b""")), _ => unreachable!("Only '<', '>', '\'', '&' and '\"' are escaped"), } loc += 1; } if escapes.is_empty() { Cow::Borrowed(raw) } else { let len = raw.len(); let mut v = Vec::with_capacity(len); let mut start = 0; for (i, r) in escapes { v.extend_from_slice(&raw[start..i]); v.extend_from_slice(r); start = i + 1; } if start < len { v.extend_from_slice(&raw[start..]); } Cow::Owned(v) } } #[derive(Clone, Eq, Debug)] /// A struct representing a DOM Element. pub struct Element { name: String, namespace: String, /// Namespace declarations pub prefixes: Prefixes, attributes: AttrMap, children: Vec, } impl<'a> From<&'a Element> for String { fn from(elem: &'a Element) -> String { let mut writer = Vec::new(); elem.write_to(&mut writer).unwrap(); String::from_utf8(writer).unwrap() } } impl FromStr for Element { type Err = Error; fn from_str(s: &str) -> Result { Element::from_reader(s.as_bytes()) } } impl PartialEq for Element { fn eq(&self, other: &Self) -> bool { if self.name() == other.name() && self.ns() == other.ns() && self.attrs().eq(other.attrs()) { if self.nodes().count() != other.nodes().count() { return false; } self.nodes() .zip(other.nodes()) .all(|(node1, node2)| node1 == node2) } else { false } } } impl Element { pub(crate) fn new>( name: String, namespace: String, prefixes: P, attributes: AttrMap, children: Vec, ) -> Element { Element { name, namespace, prefixes: prefixes.into(), attributes, children, } } /// Return a builder for an `Element` with the given `name`. /// /// # Examples /// /// ```rust /// use minidom::Element; /// use rxml::{Namespace, xml_ncname}; /// /// let elem = Element::builder("name", "namespace") /// .attr(xml_ncname!("name").to_owned(), "value") /// .append("inner") /// .build(); /// /// assert_eq!(elem.name(), "name"); /// assert_eq!(elem.ns(), "namespace".to_owned()); /// assert_eq!(elem.attr("name"), Some("value")); /// assert_eq!(elem.attr("inexistent"), None); /// assert_eq!(elem.text(), "inner"); /// ``` pub fn builder, NS: Into>(name: S, namespace: NS) -> ElementBuilder { ElementBuilder { root: Element::new( name.as_ref().to_string(), namespace.into(), None, AttrMap::new(), Vec::new(), ), } } /// Returns a bare minimum `Element` with this name. /// /// # Examples /// /// ```rust /// use minidom::Element; /// use rxml::Namespace; /// /// let bare = Element::bare("name", "namespace"); /// /// assert_eq!(bare.name(), "name"); /// assert_eq!(bare.ns(), "namespace"); /// assert_eq!(bare.attr("name"), None); /// assert_eq!(bare.text(), ""); /// ``` pub fn bare, NS: Into>(name: S, namespace: NS) -> Element { Element::new( name.into(), namespace.into(), None, AttrMap::new(), Vec::new(), ) } /// Returns a reference to the local name of this element (that is, without a possible prefix). #[must_use] pub fn name(&self) -> &str { &self.name } /// Returns a reference to the namespace of this element. #[must_use] pub fn ns(&self) -> String { self.namespace.clone() } /// Returns a reference to the value of the given attribute, if it exists, else `None`. #[must_use] pub fn attr<'a, N: Ord + Hash + Eq + ?Sized>(&'a self, name: &'a N) -> Option<&'a str> where NcName: Borrow, { if let Some(value) = self.attributes.get(&RxmlNamespace::NONE, name) { return Some(value); } None } /// Returns a reference to the value of the given namespaced attribute, if it exists, else `None`. #[must_use] pub fn attr_ns<'a, NS: Ord + Hash + Eq + ?Sized, N: Ord + Hash + Eq + ?Sized>( &'a self, ns: &'a NS, name: &'a N, ) -> Option<&'a str> where RxmlNamespace: Borrow, NcName: Borrow, { if let Some(value) = self.attributes.get(ns, name) { return Some(value); } None } /// Returns an iterator over the attributes of this element. /// /// # Example /// /// ```rust /// use minidom::Element; /// use rxml::{Namespace, xml_ncname}; /// /// let elm: Element = "".parse().unwrap(); /// /// let mut iter = elm.attrs().iter(); /// /// assert_eq!(iter.next().unwrap(), ((&Namespace::NONE, &xml_ncname!("a").to_owned()), &String::from("b"))); /// assert_eq!(iter.next(), None); /// ``` #[must_use] pub fn attrs(&self) -> &AttrMap { &self.attributes } /// Returns an iterator over the attributes of this element, with the value being a mutable /// reference. #[must_use] pub fn attrs_mut(&mut self) -> &mut AttrMap { &mut self.attributes } /// Modifies the value of an attribute. pub fn set_attr(&mut self, ns: RxmlNamespace, name: NcName, val: V) { let val = val.into_attribute_value(); if let Some(value) = self.attributes.get_mut(&ns, &name) { *value = val .expect("removing existing value via set_attr, this is not yet supported (TODO)"); // TODO return; } if let Some(val) = val { self.attributes.insert(ns.clone(), name, val); } } /// Returns whether the element has the given name and namespace. /// /// # Examples /// /// ```rust /// use minidom::{Element, NSChoice}; /// /// let elem = Element::builder("name", "namespace").build(); /// /// assert_eq!(elem.is("name", "namespace"), true); /// assert_eq!(elem.is("name", "wrong"), false); /// assert_eq!(elem.is("wrong", "namespace"), false); /// assert_eq!(elem.is("wrong", "wrong"), false); /// /// assert_eq!(elem.is("name", NSChoice::OneOf("namespace")), true); /// assert_eq!(elem.is("name", NSChoice::OneOf("foo")), false); /// assert_eq!(elem.is("name", NSChoice::AnyOf(&["foo", "namespace"])), true); /// assert_eq!(elem.is("name", NSChoice::Any), true); /// ``` pub fn is<'a, N: AsRef, NS: Into>>(&self, name: N, namespace: NS) -> bool { self.name == name.as_ref() && namespace.into().compare(self.namespace.as_ref()) } /// Returns whether the element has the given namespace. /// /// # Examples /// /// ```rust /// use minidom::{Element, NSChoice}; /// /// let elem = Element::builder("name", "namespace").build(); /// /// assert_eq!(elem.has_ns("namespace"), true); /// assert_eq!(elem.has_ns("wrong"), false); /// /// assert_eq!(elem.has_ns(NSChoice::OneOf("namespace")), true); /// assert_eq!(elem.has_ns(NSChoice::OneOf("foo")), false); /// assert_eq!(elem.has_ns(NSChoice::AnyOf(&["foo", "namespace"])), true); /// assert_eq!(elem.has_ns(NSChoice::Any), true); /// ``` pub fn has_ns<'a, NS: Into>>(&self, namespace: NS) -> bool { namespace.into().compare(self.namespace.as_ref()) } fn from_reader_inner( mut tree_builder: TreeBuilder, reader: R, ) -> Result { let mut driver = RawReader::new(reader); while let Some(event) = driver.read()? { tree_builder.process_event(event)?; if let Some(root) = tree_builder.root.take() { return Ok(root); } } Err(Error::EndOfDocument) } /// Parse a document from a `io::BufRead`. pub fn from_reader(reader: R) -> Result { Element::from_reader_inner(TreeBuilder::new(), reader) } /// Parse a document from a `io::BufRead`, allowing Prefixes to be specified. Useful to provide /// knowledge of namespaces that would have been declared on parent elements not present in the /// reader. pub fn from_reader_with_prefixes>( reader: R, prefixes: P, ) -> Result { let tree_builder = TreeBuilder::new().with_prefixes_stack([prefixes.into()].into()); Element::from_reader_inner(tree_builder, reader) } /// Output a document to a `io::Writer`. pub fn write_to(&self, writer: &mut W) -> Result<()> { self.to_writer(&mut ItemWriter::new(writer)) } /// Output a document to a `io::Writer`. pub fn write_to_decl(&self, writer: &mut W) -> Result<()> { self.to_writer_decl(&mut ItemWriter::new(writer)) } /// Output the document to an `ItemWriter` pub fn to_writer(&self, writer: &mut ItemWriter) -> Result<()> { self.write_to_inner(writer) } /// Output the document to an `ItemWriter` pub fn to_writer_decl(&self, writer: &mut ItemWriter) -> Result<()> { writer .write(Item::XmlDeclaration(XmlVersion::V1_0)) .unwrap(); // TODO: error return self.write_to_inner(writer) } /// Like `write_to()` but without the `` prelude pub fn write_to_inner(&self, writer: &mut ItemWriter) -> Result<()> { for (prefix, namespace) in self.prefixes.declared_prefixes() { assert!(writer.encoder.ns_tracker_mut().declare_fixed( prefix.as_deref().map(TryInto::try_into).transpose()?, namespace.clone().into(), )); } let namespace: RxmlNamespace = self.namespace.clone().into(); writer.write(Item::ElementHeadStart(&namespace, (*self.name).try_into()?))?; for ((ns, key), value) in &self.attributes { writer.write(Item::Attribute(&ns, key, value))?; } if !self.children.is_empty() { writer.write(Item::ElementHeadEnd)?; for child in &self.children { child.write_to_inner(writer)?; } } writer.write(Item::ElementFoot)?; Ok(()) } /// Extracts all children into a collection. pub fn take_nodes(&mut self) -> Vec { self.children.drain(..).collect() } /// Returns an iterator over references to every child node of this element. /// /// # Examples /// /// ```rust /// use minidom::Element; /// /// let elem: Element = "abc".parse().unwrap(); /// /// let mut iter = elem.nodes(); /// /// assert_eq!(iter.next().unwrap().as_text().unwrap(), "a"); /// assert_eq!(iter.next().unwrap().as_element().unwrap().name(), "c1"); /// assert_eq!(iter.next().unwrap().as_text().unwrap(), "b"); /// assert_eq!(iter.next().unwrap().as_element().unwrap().name(), "c2"); /// assert_eq!(iter.next().unwrap().as_text().unwrap(), "c"); /// assert_eq!(iter.next(), None); /// ``` #[inline] pub fn nodes(&self) -> Nodes<'_> { self.children.iter() } /// Returns an iterator over mutable references to every child node of this element. #[inline] pub fn nodes_mut(&mut self) -> NodesMut<'_> { self.children.iter_mut() } /// Returns an iterator over references to every child element of this element. /// /// # Examples /// /// ```rust /// use minidom::Element; /// /// let elem: Element = "hellothisisignored".parse().unwrap(); /// /// let mut iter = elem.children(); /// assert_eq!(iter.next().unwrap().name(), "child1"); /// assert_eq!(iter.next().unwrap().name(), "child2"); /// assert_eq!(iter.next().unwrap().name(), "child3"); /// assert_eq!(iter.next(), None); /// ``` #[inline] #[must_use] pub fn children(&self) -> Children<'_> { Children { iter: self.children.iter(), } } /// Returns an iterator over mutable references to every child element of this element. #[inline] #[must_use] pub fn children_mut(&mut self) -> ChildrenMut<'_> { ChildrenMut { iter: self.children.iter_mut(), } } /// Returns an iterator over the child Elements, draining the element of /// all its child nodes **including text!** /// /// This is a bit of a footgun, so we make this hidden in the docs (it /// needs to be pub for macro use). Once `extract_if` /// ([rust#43244](https://github.com/rust-lang/rust/issues/43244)) /// is stabilized, we can replace this with a take_children which doesn't /// remove text nodes. #[inline] #[doc(hidden)] pub fn take_contents_as_children(&mut self) -> ContentsAsChildren<'_> { ContentsAsChildren { iter: self.children.drain(..), } } /// Returns an iterator over references to every text node of this element. /// /// # Examples /// /// ```rust /// use minidom::Element; /// /// let elem: Element = "hello world!".parse().unwrap(); /// /// let mut iter = elem.texts(); /// assert_eq!(iter.next().unwrap(), "hello"); /// assert_eq!(iter.next().unwrap(), " world!"); /// assert_eq!(iter.next(), None); /// ``` #[inline] #[must_use] pub fn texts(&self) -> Texts<'_> { Texts { iter: self.children.iter(), } } /// Returns an iterator over mutable references to every text node of this element. #[inline] #[must_use] pub fn texts_mut(&mut self) -> TextsMut<'_> { TextsMut { iter: self.children.iter_mut(), } } /// Appends a child node to the `Element`, returning the appended node. /// /// # Examples /// /// ```rust /// use minidom::Element; /// /// let mut elem = Element::bare("root", "ns1"); /// /// assert_eq!(elem.children().count(), 0); /// /// elem.append_child(Element::bare("child", "ns1")); /// /// { /// let mut iter = elem.children(); /// assert_eq!(iter.next().unwrap().name(), "child"); /// assert_eq!(iter.next(), None); /// } /// /// let child = elem.append_child(Element::bare("new", "ns1")); /// /// assert_eq!(child.name(), "new"); /// ``` pub fn append_child(&mut self, child: Element) -> &mut Element { self.children.push(Node::Element(child)); if let Node::Element(ref mut cld) = *self.children.last_mut().unwrap() { cld } else { unreachable!() } } /// Appends a text node to an `Element`. /// /// # Examples /// /// ```rust /// use minidom::Element; /// /// let mut elem = Element::bare("node", "ns1"); /// /// assert_eq!(elem.text(), ""); /// /// elem.append_text_node("text"); /// /// assert_eq!(elem.text(), "text"); /// ``` pub fn append_text_node>(&mut self, child: S) { self.children.push(Node::Text(child.into())); } /// Appends a string as plain text to an `Element`. /// /// If the last child node of the element is a text node, the string will be appended to it. /// Otherwise, a new text node will be created. /// /// # Examples /// /// ```rust /// use minidom::Element; /// /// let mut elem = Element::bare("node", "ns1"); /// /// assert_eq!(elem.text(), ""); /// /// elem.append_text_node("text"); /// /// elem.append_text(" and more text"); /// /// assert_eq!(elem.nodes().count(), 1); /// ``` pub fn append_text>(&mut self, text: S) { if let Some(Node::Text(ref mut child)) = self.children.last_mut() { child.push_str(&text.into()); } else { self.append_text_node(text); } } /// Appends a node to an `Element`. /// /// # Examples /// /// ```rust /// use minidom::{Element, Node}; /// /// let mut elem = Element::bare("node", "ns1"); /// /// elem.append_node(Node::Text("hello".to_owned())); /// /// assert_eq!(elem.text(), "hello"); /// ``` pub fn append_node(&mut self, node: Node) { self.children.push(node); } /// Returns the concatenation of all text nodes in the `Element`. /// /// # Examples /// /// ```rust /// use minidom::Element; /// /// let elem: Element = "hello, world!".parse().unwrap(); /// /// assert_eq!(elem.text(), "hello, world!"); /// ``` #[must_use] pub fn text(&self) -> String { self.texts().fold(String::new(), |ret, new| ret + new) } /// Returns a reference to the first child element with the specific name and namespace, if it /// exists in the direct descendants of this `Element`, else returns `None`. /// /// # Examples /// /// ```rust /// use minidom::{Element, NSChoice}; /// /// let elem: Element = r#""#.parse().unwrap(); /// assert!(elem.get_child("a", "ns").unwrap().is("a", "ns")); /// assert!(elem.get_child("a", "other_ns").unwrap().is("a", "other_ns")); /// assert!(elem.get_child("b", "ns").unwrap().is("b", "ns")); /// assert_eq!(elem.get_child("c", "ns"), None); /// assert_eq!(elem.get_child("b", "other_ns"), None); /// assert_eq!(elem.get_child("a", "inexistent_ns"), None); /// ``` pub fn get_child<'a, N: AsRef, NS: Into>>( &self, name: N, namespace: NS, ) -> Option<&Element> { let namespace = namespace.into(); for fork in &self.children { if let Node::Element(ref e) = *fork { if e.is(name.as_ref(), namespace) { return Some(e); } } } None } /// Returns a mutable reference to the first child element with the specific name and namespace, /// if it exists in the direct descendants of this `Element`, else returns `None`. pub fn get_child_mut<'a, N: AsRef, NS: Into>>( &mut self, name: N, namespace: NS, ) -> Option<&mut Element> { let namespace = namespace.into(); for fork in &mut self.children { if let Node::Element(ref mut e) = *fork { if e.is(name.as_ref(), namespace) { return Some(e); } } } None } /// Returns whether a specific child with this name and namespace exists in the direct /// descendants of the `Element`. /// /// # Examples /// /// ```rust /// use minidom::{Element, NSChoice}; /// /// let elem: Element = r#""#.parse().unwrap(); /// assert_eq!(elem.has_child("a", "other_ns"), true); /// assert_eq!(elem.has_child("a", "ns"), true); /// assert_eq!(elem.has_child("a", "inexistent_ns"), false); /// assert_eq!(elem.has_child("b", "ns"), true); /// assert_eq!(elem.has_child("b", "other_ns"), false); /// assert_eq!(elem.has_child("b", "inexistent_ns"), false); /// ``` pub fn has_child<'a, N: AsRef, NS: Into>>( &self, name: N, namespace: NS, ) -> bool { self.get_child(name, namespace).is_some() } /// Removes the first child with this name and namespace, if it exists, and returns an /// `Option` containing this child if it succeeds. /// Returns `None` if no child matches this name and namespace. /// /// # Examples /// /// ```rust /// use minidom::{Element, NSChoice}; /// /// let mut elem: Element = r#""#.parse().unwrap(); /// assert!(elem.remove_child("a", "ns").unwrap().is("a", "ns")); /// assert!(elem.remove_child("a", "ns").is_none()); /// assert!(elem.remove_child("inexistent", "inexistent").is_none()); /// ``` pub fn remove_child<'a, N: AsRef, NS: Into>>( &mut self, name: N, namespace: NS, ) -> Option { let name = name.as_ref(); let namespace = namespace.into(); let idx = self.children.iter().position(|x| { if let Node::Element(ref elm) = x { elm.is(name, namespace) } else { false } })?; self.children.remove(idx).into_element() } /// Remove the leading nodes up to the first child element and /// return it pub fn unshift_child(&mut self) -> Option { while !self.children.is_empty() { if let Some(el) = self.children.remove(0).into_element() { return Some(el); } } None } } /// An iterator over references to child elements of an `Element`. pub struct Children<'a> { iter: slice::Iter<'a, Node>, } impl<'a> Iterator for Children<'a> { type Item = &'a Element; fn next(&mut self) -> Option<&'a Element> { for item in &mut self.iter { if let Node::Element(ref child) = *item { return Some(child); } } None } } /// An iterator over mutable references to child elements of an `Element`. pub struct ChildrenMut<'a> { iter: slice::IterMut<'a, Node>, } impl<'a> Iterator for ChildrenMut<'a> { type Item = &'a mut Element; fn next(&mut self) -> Option<&'a mut Element> { for item in &mut self.iter { if let Node::Element(ref mut child) = *item { return Some(child); } } None } } /// An iterator over references to child elements of an `Element`. pub struct ContentsAsChildren<'a> { iter: alloc::vec::Drain<'a, Node>, } impl Iterator for ContentsAsChildren<'_> { type Item = Element; fn next(&mut self) -> Option { for item in &mut self.iter { if let Node::Element(child) = item { return Some(child); } } None } } /// An iterator over references to child text nodes of an `Element`. pub struct Texts<'a> { iter: slice::Iter<'a, Node>, } impl<'a> Iterator for Texts<'a> { type Item = &'a str; fn next(&mut self) -> Option<&'a str> { for item in &mut self.iter { if let Node::Text(ref child) = *item { return Some(child); } } None } } /// An iterator over mutable references to child text nodes of an `Element`. pub struct TextsMut<'a> { iter: slice::IterMut<'a, Node>, } impl<'a> Iterator for TextsMut<'a> { type Item = &'a mut String; fn next(&mut self) -> Option<&'a mut String> { for item in &mut self.iter { if let Node::Text(ref mut child) = *item { return Some(child); } } None } } /// An iterator over references to all child nodes of an `Element`. pub type Nodes<'a> = slice::Iter<'a, Node>; /// An iterator over mutable references to all child nodes of an `Element`. pub type NodesMut<'a> = slice::IterMut<'a, Node>; /// A builder for `Element`s. pub struct ElementBuilder { root: Element, } impl ElementBuilder { /// Sets a custom prefix. It is not possible to set the same prefix twice. pub fn prefix>( mut self, prefix: Prefix, namespace: S, ) -> Result { if self.root.prefixes.get(&prefix).is_some() { return Err(Error::DuplicatePrefix); } self.root.prefixes.insert(prefix, namespace.into()); Ok(self) } /// Sets an attribute. #[must_use] pub fn attr(mut self, name: NcName, value: V) -> ElementBuilder { self.root.set_attr(RxmlNamespace::NONE, name, value); self } /// Sets an attribute. #[must_use] pub fn attr_ns( mut self, ns: RxmlNamespace, name: NcName, value: V, ) -> ElementBuilder { self.root.set_attr(ns, name, value); self } /// Appends anything implementing `Into` into the tree. #[must_use] pub fn append>(mut self, node: T) -> ElementBuilder { self.root.append_node(node.into()); self } /// Appends an iterator of things implementing `Into` into the tree. #[must_use] pub fn append_all, I: IntoIterator>( mut self, iter: I, ) -> ElementBuilder { for node in iter { self.root.append_node(node.into()); } self } /// Builds the `Element`. #[must_use] pub fn build(self) -> Element { self.root } } #[cfg(test)] mod tests { use super::*; use rxml::xml_ncname; use std::collections::BTreeMap; #[test] fn test_element_new() { let mut attrs = AttrMap::new(); attrs.insert( String::from("namespace").into(), xml_ncname!("name").to_owned(), "value".to_string(), ); let elem = Element::new( "name".to_owned(), "namespace".to_owned(), (None, "namespace".to_owned()), attrs, Vec::new(), ); assert_eq!(elem.name(), "name"); assert_eq!(elem.ns(), "namespace".to_owned()); assert_eq!(elem.attr_ns("namespace", "name"), Some("value")); assert_eq!(elem.attr("inexistent"), None); } #[test] fn test_from_reader_simple() { let xml = b""; let elem = Element::from_reader(&xml[..]); let elem2 = Element::builder("foo", "ns1").build(); assert_eq!(elem.unwrap(), elem2); } #[test] fn test_from_reader_nested() { let xml = b""; let elem = Element::from_reader(&xml[..]); let nested = Element::builder("bar", "ns1") .attr(xml_ncname!("baz").to_owned(), "qxx") .build(); let elem2 = Element::builder("foo", "ns1").append(nested).build(); assert_eq!(elem.unwrap(), elem2); } #[test] fn test_from_reader_with_prefix() { let xml = b""; let elem = Element::from_reader(&xml[..]); let nested = Element::builder("bar", "ns1") .attr(xml_ncname!("baz").to_owned(), "qxx") .build(); let elem2 = Element::builder("foo", "ns1").append(nested).build(); assert_eq!(elem.unwrap(), elem2); } #[test] fn test_from_reader_split_prefix() { let xml = b""; let elem = Element::from_reader(&xml[..]).unwrap(); assert_eq!(elem.name(), String::from("bar")); assert_eq!(elem.ns(), String::from("ns1")); // Ensure the prefix is properly added to the store assert_eq!( elem.prefixes.get(&Some(String::from("foo"))), Some(&String::from("ns1")) ); } #[test] fn parses_spectest_xml() { // From: https://gitlab.com/lumi/minidom-rs/issues/8 let xml = br#" "#; let _ = Element::from_reader(&xml[..]).unwrap(); } #[test] fn does_not_unescape_cdata() { let xml = b"]]>"; let elem = Element::from_reader(&xml[..]).unwrap(); assert_eq!(elem.text(), "'>blah"); } #[test] fn test_compare_all_ns() { let xml = b""; let elem = Element::from_reader(&xml[..]).unwrap(); let elem2 = elem.clone(); let xml3 = b""; let elem3 = Element::from_reader(&xml3[..]).unwrap(); let xml4 = b""; let elem4 = Element::from_reader(&xml4[..]).unwrap(); assert_eq!(elem, elem2); assert_eq!(elem, elem3); assert_eq!(elem, elem4); } #[test] fn test_compare_empty_children() { let elem1 = Element::bare("p", ""); let elem2 = Element::builder("p", "") .append(Node::Element(Element::bare("span", ""))) .build(); assert_ne!(elem1, elem2); } #[test] fn test_from_reader_with_prefixes() { let xml = b""; let elem = Element::from_reader_with_prefixes(&xml[..], String::from("jabber:client")).unwrap(); let xml2 = b""; let elem2 = Element::from_reader(&xml2[..]).unwrap(); assert_eq!(elem, elem2); } #[test] fn test_from_reader_with_prefixes_serialization() { let prefixes: BTreeMap, String> = { let mut tmp = BTreeMap::new(); tmp.insert(None, String::from("foo")); tmp.insert(Some(String::from("test")), String::from("bar")); tmp }; let input = r#""#; let output = r#""#; let elem = Element::from_reader_with_prefixes(input.as_ref(), prefixes).unwrap(); assert_eq!(String::from(&elem), output); } #[test] fn failure_with_duplicate_namespace() { let _: Element = r###" "### .parse() .unwrap(); } } minidom-0.18.0/src/error.rs000064400000000000000000000043331046102023000136370ustar 00000000000000// Copyright (c) 2020 lumi // Copyright (c) 2020 Emmanuel Gil Peyrot // Copyright (c) 2020 Bastien Orivel // Copyright (c) 2020 Astro // Copyright (c) 2020 Maxime “pep” Buquet // Copyright (c) 2020 Matt Bilker // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //! Provides an error type for this crate. use std::io; use thiserror::Error; /// Our main error type. #[derive(Debug, Error)] pub enum Error { /// Error from rxml parsing or writing #[error("XML error: {0}")] XmlError(#[from] rxml::Error), /// I/O error from accessing the source or destination. /// /// Even though the [`rxml`] crate emits its errors through /// [`io::Error`] when using it with [`BufRead`][`io::BufRead`], /// any rxml errors will still be reported through the /// [`XmlError`][`Self::XmlError`] variant. #[error("I/O error: {0}")] Io(io::Error), /// An error which is returned when the end of the document was reached prematurely. #[error("the end of the document has been reached prematurely")] EndOfDocument, /// An error which is returned when an element being serialized doesn't contain a prefix /// (be it None or Some(_)). #[error("the prefix is invalid")] InvalidPrefix, /// An error which is returned when an element doesn't contain a namespace #[error("the XML element is missing a namespace")] MissingNamespace, /// An error which is returned when a prefixed is defined twice #[error("the prefix is already defined")] DuplicatePrefix, } impl From for Error { fn from(other: io::Error) -> Self { match other.downcast::() { Ok(e) => Self::XmlError(e), Err(e) => Self::Io(e), } } } impl From for Error { fn from(err: rxml::strings::Error) -> Error { rxml::error::Error::from(err).into() } } /// Our simplified Result type. pub type Result = ::core::result::Result; minidom-0.18.0/src/lib.rs000064400000000000000000000052011046102023000132470ustar 00000000000000// Copyright (c) 2020 lumi // Copyright (c) 2020 Emmanuel Gil Peyrot // Copyright (c) 2020 Bastien Orivel // Copyright (c) 2020 Astro // Copyright (c) 2020 Maxime “pep” Buquet // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #![deny(missing_docs)] #![cfg_attr(docsrs, feature(doc_cfg))] #![cfg_attr(docsrs, doc(auto_cfg))] //! A minimal DOM crate built on top of rxml, targeting exclusively the subset of XML useful //! for XMPP. //! //! This library exports an `Element` struct which represents a DOM tree. //! //! # Example //! //! Run with `cargo run --example articles`. Located in `examples/articles.rs`. //! //! ```rust //! extern crate minidom; //! //! use minidom::Element; //! //! const DATA: &'static str = r#" //!
//! 10 Terrible Bugs You Would NEVER Believe Happened //! //! Rust fixed them all. <3 //! //!
//!
//! BREAKING NEWS: Physical Bug Jumps Out Of Programmer's Screen //! //! Just kidding! //! //!
//!
"#; //! //! const ARTICLE_NS: &'static str = "article"; //! //! #[derive(Debug)] //! pub struct Article { //! title: String, //! body: String, //! } //! //! fn main() { //! let root: Element = DATA.parse().unwrap(); //! //! let mut articles: Vec
= Vec::new(); //! //! for child in root.children() { //! if child.is("article", ARTICLE_NS) { //! let title = child.get_child("title", ARTICLE_NS).unwrap().text(); //! let body = child.get_child("body", ARTICLE_NS).unwrap().text(); //! articles.push(Article { //! title: title, //! body: body.trim().to_owned(), //! }); //! } //! } //! //! println!("{:?}", articles); //! } //! ``` //! //! # Usage //! //! To use `minidom`, add this to your `Cargo.toml` under `dependencies`: //! //! ```toml,ignore //! minidom = "*" //! ``` extern crate alloc; pub mod convert; pub mod element; pub mod error; mod namespaces; pub mod node; mod prefixes; pub mod tree_builder; #[cfg(test)] mod tests; pub use convert::IntoAttributeValue; pub use element::{Children, ChildrenMut, Element, ElementBuilder}; pub use error::{Error, Result}; pub use namespaces::NSChoice; pub use node::Node; pub use rxml; minidom-0.18.0/src/namespaces.rs000064400000000000000000000024401046102023000146220ustar 00000000000000// Copyright (c) 2020 Emmanuel Gil Peyrot // Copyright (c) 2020 Astro // Copyright (c) 2020 Maxime “pep” Buquet // Copyright (c) 2020 Xidorn Quan // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #[derive(Clone, Copy, PartialEq, Eq, Debug)] /// Use to compare namespaces pub enum NSChoice<'a> { /// The element must have no namespace None, /// The element's namespace must match the specified namespace OneOf(&'a str), /// The element's namespace must be in the specified vector AnyOf(&'a [&'a str]), /// The element can have any namespace, or no namespace Any, } impl<'a> From<&'a str> for NSChoice<'a> { fn from(ns: &'a str) -> NSChoice<'a> { NSChoice::OneOf(ns) } } impl NSChoice<'_> { pub(crate) fn compare(&self, ns: &str) -> bool { match (ns, &self) { (_, NSChoice::None) => false, (_, NSChoice::Any) => true, (ns, NSChoice::OneOf(wanted_ns)) => &ns == wanted_ns, (ns, NSChoice::AnyOf(wanted_nss)) => wanted_nss.iter().any(|w| &ns == w), } } } minidom-0.18.0/src/node.rs000064400000000000000000000133231046102023000134320ustar 00000000000000// Copyright (c) 2020 lumi // Copyright (c) 2020 Emmanuel Gil Peyrot // Copyright (c) 2020 Maxime “pep” Buquet // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //! Provides the `Node` struct, which represents a node in the DOM. use crate::element::{Element, ElementBuilder, ItemWriter}; use crate::error::Result; use alloc::string::String; use rxml::writer::Item; use std::io; /// A node in an element tree. #[derive(Clone, Debug, Eq)] pub enum Node { /// An `Element`. Element(Element), /// A text node. Text(String), } impl Node { /// Turns this into a reference to an `Element` if this is an element node. /// Else this returns `None`. /// /// # Examples /// /// ```rust /// use minidom::Node; /// /// let elm = Node::Element("".parse().unwrap()); /// let txt = Node::Text("meow".to_owned()); /// /// assert_eq!(elm.as_element().unwrap().name(), "meow"); /// assert_eq!(txt.as_element(), None); /// ``` #[must_use] pub fn as_element(&self) -> Option<&Element> { match *self { Node::Element(ref e) => Some(e), Node::Text(_) => None, } } /// Turns this into a mutable reference of an `Element` if this is an element node. /// Else this returns `None`. /// /// # Examples /// /// ```rust /// use minidom::Node; /// /// let mut elm = Node::Element("".parse().unwrap()); /// let mut txt = Node::Text("meow".to_owned()); /// /// assert_eq!(elm.as_element_mut().unwrap().name(), "meow"); /// assert_eq!(txt.as_element_mut(), None); /// ``` #[must_use] pub fn as_element_mut(&mut self) -> Option<&mut Element> { match *self { Node::Element(ref mut e) => Some(e), Node::Text(_) => None, } } /// Turns this into an `Element`, consuming self, if this is an element node. /// Else this returns `None`. /// /// # Examples /// /// ```rust /// use minidom::Node; /// /// let elm = Node::Element("".parse().unwrap()); /// let txt = Node::Text("meow".to_owned()); /// /// assert_eq!(elm.into_element().unwrap().name(), "meow"); /// assert_eq!(txt.into_element(), None); /// ``` #[must_use] pub fn into_element(self) -> Option { match self { Node::Element(e) => Some(e), Node::Text(_) => None, } } /// Turns this into an `&str` if this is a text node. /// Else this returns `None`. /// /// # Examples /// /// ```rust /// use minidom::Node; /// /// let elm = Node::Element("".parse().unwrap()); /// let txt = Node::Text("meow".to_owned()); /// /// assert_eq!(elm.as_text(), None); /// assert_eq!(txt.as_text().unwrap(), "meow"); /// ``` #[must_use] pub fn as_text(&self) -> Option<&str> { match *self { Node::Element(_) => None, Node::Text(ref s) => Some(s), } } /// Turns this into an `&mut String` if this is a text node. /// Else this returns `None`. /// /// # Examples /// /// ```rust /// use minidom::Node; /// /// let mut elm = Node::Element("".parse().unwrap()); /// let mut txt = Node::Text("meow".to_owned()); /// /// assert_eq!(elm.as_text_mut(), None); /// { /// let text_mut = txt.as_text_mut().unwrap(); /// assert_eq!(text_mut, "meow"); /// text_mut.push_str("zies"); /// assert_eq!(text_mut, "meowzies"); /// } /// assert_eq!(txt.as_text().unwrap(), "meowzies"); /// ``` #[must_use] pub fn as_text_mut(&mut self) -> Option<&mut String> { match *self { Node::Element(_) => None, Node::Text(ref mut s) => Some(s), } } /// Turns this into an `String`, consuming self, if this is a text node. /// Else this returns `None`. /// /// # Examples /// /// ```rust /// use minidom::Node; /// /// let elm = Node::Element("".parse().unwrap()); /// let txt = Node::Text("meow".to_owned()); /// /// assert_eq!(elm.into_text(), None); /// assert_eq!(txt.into_text().unwrap(), "meow"); /// ``` #[must_use] pub fn into_text(self) -> Option { match self { Node::Element(_) => None, Node::Text(s) => Some(s), } } #[doc(hidden)] pub(crate) fn write_to_inner(&self, writer: &mut ItemWriter) -> Result<()> { match self { Node::Element(elmt) => elmt.write_to_inner(writer)?, Node::Text(s) => { writer.write(Item::Text(s))?; } } Ok(()) } } impl From for Node where I: Into, { fn from(elm: I) -> Node { Node::Element(elm.into()) } } impl From for Node { fn from(s: String) -> Node { Node::Text(s) } } impl<'a> From<&'a str> for Node { fn from(s: &'a str) -> Node { Node::Text(s.to_owned()) } } impl From for Node { fn from(builder: ElementBuilder) -> Node { Node::Element(builder.build()) } } impl PartialEq for Node { fn eq(&self, other: &Self) -> bool { match (self, other) { (Node::Element(elem1), Node::Element(elem2)) => elem1 == elem2, (Node::Text(text1), Node::Text(text2)) => text1 == text2, _ => false, } } } minidom-0.18.0/src/prefixes.rs000064400000000000000000000050261046102023000143330ustar 00000000000000// Copyright (c) 2020 Emmanuel Gil Peyrot // Copyright (c) 2020 Astro // Copyright (c) 2020 Maxime “pep” Buquet // Copyright (c) 2020 Xidorn Quan // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use alloc::collections::BTreeMap; use alloc::string::String; use core::fmt; pub type Prefix = Option; pub type Namespace = String; #[derive(Clone, Default, PartialEq, Eq)] pub struct Prefixes { prefixes: BTreeMap, } impl fmt::Debug for Prefixes { // TODO: Fix end character fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Prefixes(")?; for (prefix, namespace) in &self.prefixes { if let Some(prefix) = prefix { write!(f, "xmlns:{prefix}={namespace:?} ")?; } else { write!(f, "xmlns={namespace:?} ")?; } } write!(f, ")") } } impl Prefixes { pub fn declared_prefixes(&self) -> &BTreeMap { &self.prefixes } pub fn get(&self, prefix: &Prefix) -> Option<&Namespace> { self.prefixes.get(prefix) } pub(crate) fn insert>(&mut self, prefix: Prefix, namespace: S) { self.prefixes.insert(prefix, namespace.into()); } } impl From> for Prefixes { fn from(prefixes: BTreeMap) -> Self { Prefixes { prefixes } } } impl From> for Prefixes { fn from(namespace: Option) -> Self { match namespace { None => Self::default(), Some(namespace) => Self::from(namespace), } } } impl From for Prefixes { fn from(namespace: Namespace) -> Self { let mut prefixes = BTreeMap::new(); prefixes.insert(None, namespace); Prefixes { prefixes } } } impl From<(Prefix, Namespace)> for Prefixes { fn from(prefix_namespace: (Prefix, Namespace)) -> Self { let (prefix, namespace) = prefix_namespace; let mut prefixes = BTreeMap::new(); prefixes.insert(prefix, namespace); Prefixes { prefixes } } } impl From<(String, String)> for Prefixes { fn from(prefix_namespace: (String, String)) -> Self { let (prefix, namespace) = prefix_namespace; Self::from((Some(prefix), namespace)) } } minidom-0.18.0/src/tests.rs000064400000000000000000000355111046102023000136520ustar 00000000000000// Copyright (c) 2020 lumi // Copyright (c) 2020 Emmanuel Gil Peyrot // Copyright (c) 2020 Bastien Orivel // Copyright (c) 2020 Astro // Copyright (c) 2020 Maxime “pep” Buquet // Copyright (c) 2020 Yue Liu // Copyright (c) 2020 Matt Bilker // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use crate::element::Element; use crate::error::Error; use alloc::format; use alloc::string::String; use alloc::vec::Vec; use rxml::{xml_ncname, Namespace as RxmlNamespace}; const TEST_STRING: &'static [u8] = br#"meownya"#; fn build_test_tree() -> Element { let mut root = Element::builder("root", "root_ns") .attr_ns(RxmlNamespace::XML, xml_ncname!("lang").to_owned(), "en") .attr(xml_ncname!("a").to_owned(), "b") .build(); root.append_text_node("meow"); let child = Element::builder("child", "root_ns") .attr(xml_ncname!("c").to_owned(), "d") .build(); root.append_child(child); let other_child = Element::builder("child", "child_ns") .attr(xml_ncname!("d").to_owned(), "e") .attr_ns(RxmlNamespace::XML, xml_ncname!("lang").to_owned(), "fr") .build(); root.append_child(other_child); root.append_text_node("nya"); root } #[test] fn reader_works() { assert_eq!( Element::from_reader(TEST_STRING).unwrap(), build_test_tree() ); } #[test] fn reader_deduplicate_prefixes() { // The reader shouldn't complain that "child" doesn't have a namespace. It should reuse the // parent ns with the same prefix. let _: Element = r#""#.parse().unwrap(); let _: Element = r#""#.parse().unwrap(); let _: Element = r#""# .parse() .unwrap(); match r#""#.parse::() { Err(Error::MissingNamespace) => (), Err(err) => panic!("No or wrong error: {:?}", err), Ok(elem) => panic!( "Got Element: {}; was expecting Error::MissingNamespace", String::from(&elem) ), } } #[test] fn reader_no_deduplicate_sibling_prefixes() { // The reader shouldn't reuse the sibling's prefixes match r#""#.parse::() { Err(Error::MissingNamespace) => (), Err(err) => panic!("No or wrong error: {:?}", err), Ok(elem) => panic!( "Got Element:\n{:?}\n{}\n; was expecting Error::MissingNamespace", elem, String::from(&elem) ), } } #[test] fn test_real_data() { let correction = Element::builder("replace", "urn:xmpp:message-correct:0").build(); let body = Element::builder("body", "jabber:client").build(); let message = Element::builder("message", "jabber:client") .append(body) .append(correction) .build(); let _stream = Element::builder("stream", "http://etherx.jabber.org/streams") .prefix( Some(String::from("stream")), "http://etherx.jabber.org/streams", ) .unwrap() .prefix(None, "jabber:client") .unwrap() .append(message) .build(); let jid = Element::builder("jid", "urn:xmpp:presence:0").build(); let nick = Element::builder("nick", "urn:xmpp:presence:0").build(); let mix = Element::builder("mix", "urn:xmpp:presence:0") .append(jid) .append(nick) .build(); let show = Element::builder("show", "jabber:client").build(); let status = Element::builder("status", "jabber:client").build(); let presence = Element::builder("presence", "jabber:client") .append(show) .append(status) .append(mix) .build(); let item = Element::builder("item", "http://jabber.org/protocol/pubsub") .append(presence) .build(); let items = Element::builder("items", "http://jabber.org/protocol/pubsub") .append(item) .build(); let pubsub = Element::builder("pubsub", "http://jabber.org/protocol/pubsub") .append(items) .build(); let iq = Element::builder("iq", "jabber:client") .append(pubsub) .build(); let _stream = Element::builder("stream", "http://etherx.jabber.org/streams") .prefix( Some(String::from("stream")), "http://etherx.jabber.org/streams", ) .unwrap() .prefix(None, "jabber:client") .unwrap() .append(iq) .build(); } #[test] fn writer_works() { let root = build_test_tree(); let mut writer = Vec::new(); { root.write_to(&mut writer).unwrap(); } assert_eq!(writer, TEST_STRING); } #[test] fn writer_with_decl_works() { let root = build_test_tree(); let mut writer = Vec::new(); { root.write_to_decl(&mut writer).unwrap(); } let result = format!( "\n{}", String::from_utf8(TEST_STRING.to_owned()).unwrap() ); assert_eq!(String::from_utf8(writer).unwrap(), result); } #[test] fn writer_with_prefix() { let root = Element::builder("root", "ns1") .prefix(Some(String::from("p1")), "ns1") .unwrap() .prefix(None, "ns2") .unwrap() .build(); assert_eq!( String::from(&root), r#""#, ); } #[test] fn writer_no_prefix_namespace() { let root = Element::builder("root", "ns1").build(); // TODO: Note that this isn't exactly equal to a None prefix. it's just that the None prefix is // the most obvious when it's not already used. Maybe fix tests so that it only checks that the // prefix used equals the one declared for the namespace. assert_eq!(String::from(&root), r#""#); } #[test] fn writer_no_prefix_namespace_child() { let child = Element::builder("child", "ns1").build(); let root = Element::builder("root", "ns1").append(child).build(); // TODO: Same remark as `writer_no_prefix_namespace`. assert_eq!(String::from(&root), r#""#); let child = Element::builder("child", "ns2") .prefix(None, "ns3") .unwrap() .build(); let root = Element::builder("root", "ns1").append(child).build(); // TODO: Same remark as `writer_no_prefix_namespace`. assert_eq!( String::from(&root), r#""# ); } #[test] fn writer_prefix_namespace_child() { let child = Element::builder("child", "ns1").build(); let root = Element::builder("root", "ns1") .prefix(Some(String::from("p1")), "ns1") .unwrap() .append(child) .build(); assert_eq!( String::from(&root), r#""# ); } #[test] fn writer_with_prefix_deduplicate() { let child = Element::builder("child", "ns1") // .prefix(Some(String::from("p1")), "ns1") .build(); let root = Element::builder("root", "ns1") .prefix(Some(String::from("p1")), "ns1") .unwrap() .prefix(None, "ns2") .unwrap() .append(child) .build(); assert_eq!( String::from(&root), r#""#, ); // Ensure descendants don't just reuse ancestors' prefixes that have been shadowed in between let grandchild = Element::builder("grandchild", "ns1").build(); let child = Element::builder("child", "ns2").append(grandchild).build(); let root = Element::builder("root", "ns1").append(child).build(); assert_eq!( String::from(&root), r#""#, ); } #[test] fn writer_escapes_attributes() { let root = Element::builder("root", "ns1") .attr(xml_ncname!("a").to_owned(), "\"Air\" quotes") .build(); let mut writer = Vec::new(); { root.write_to(&mut writer).unwrap(); } assert_eq!( String::from_utf8(writer).unwrap(), r#""# ); } #[test] fn writer_escapes_text() { let root = Element::builder("root", "ns1").append("<3").build(); let mut writer = Vec::new(); { root.write_to(&mut writer).unwrap(); } assert_eq!( String::from_utf8(writer).unwrap(), r#"<3"# ); } #[test] fn builder_works() { let elem = Element::builder("a", "b") .attr(xml_ncname!("c").to_owned(), "d") .append(Element::builder("child", "b")) .append("e") .build(); assert_eq!(elem.name(), "a"); assert_eq!(elem.ns(), "b".to_owned()); assert_eq!(elem.attr("c"), Some("d")); assert_eq!(elem.attr("x"), None); assert_eq!(elem.text(), "e"); assert!(elem.has_child("child", "b")); assert!(elem.is("a", "b")); } #[test] fn children_iter_works() { let root = build_test_tree(); let mut iter = root.children(); assert!(iter.next().unwrap().is("child", "root_ns")); assert!(iter.next().unwrap().is("child", "child_ns")); assert_eq!(iter.next(), None); } #[test] fn get_child_works() { let root = build_test_tree(); assert_eq!(root.get_child("child", "inexistent_ns"), None); assert_eq!(root.get_child("not_a_child", "root_ns"), None); assert!(root .get_child("child", "root_ns") .unwrap() .is("child", "root_ns")); assert!(root .get_child("child", "child_ns") .unwrap() .is("child", "child_ns")); assert_eq!( root.get_child("child", "root_ns").unwrap().attr("c"), Some("d") ); assert_eq!( root.get_child("child", "child_ns").unwrap().attr("d"), Some("e") ); } #[test] fn namespace_propagation_works() { let mut root = Element::builder("root", "root_ns").build(); let mut child = Element::bare("child", "root_ns"); let grandchild = Element::bare("grandchild", "root_ns"); child.append_child(grandchild); root.append_child(child); assert_eq!(root.get_child("child", "root_ns").unwrap().ns(), root.ns()); assert_eq!( root.get_child("child", "root_ns") .unwrap() .get_child("grandchild", "root_ns") .unwrap() .ns(), root.ns() ); } #[test] fn two_elements_with_same_arguments_different_order_are_equal() { let elem1: Element = "".parse().unwrap(); let elem2: Element = "".parse().unwrap(); assert_eq!(elem1, elem2); let elem1: Element = "".parse().unwrap(); let elem2: Element = "".parse().unwrap(); assert_ne!(elem1, elem2); } #[test] fn namespace_attributes_works() { let root = Element::from_reader(TEST_STRING).unwrap(); assert_eq!(Some("en"), root.attr_ns(RxmlNamespace::xml(), "lang")); assert_eq!( "fr", root.get_child("child", "child_ns") .unwrap() .attr_ns(RxmlNamespace::xml(), "lang") .unwrap() ); } #[test] fn wrongly_closed_elements_error() { let elem1 = "".parse::(); assert!(elem1.is_err()); let elem1 = "".parse::(); assert!(elem1.is_err()); let elem1 = "".parse::(); assert!(elem1.is_ok()); } #[test] fn namespace_simple() { let elem: Element = "".parse().unwrap(); assert_eq!(elem.name(), "message"); assert_eq!(elem.ns(), "jabber:client".to_owned()); } #[test] fn namespace_prefixed() { let elem: Element = "" .parse() .unwrap(); assert_eq!(elem.name(), "features"); assert_eq!(elem.ns(), "http://etherx.jabber.org/streams".to_owned(),); } #[test] fn namespace_inherited_simple() { let elem: Element = "" .parse() .unwrap(); assert_eq!(elem.name(), "stream"); assert_eq!(elem.ns(), "jabber:client".to_owned()); let child = elem.children().next().unwrap(); assert_eq!(child.name(), "message"); assert_eq!(child.ns(), "jabber:client".to_owned()); } #[test] fn namespace_inherited_prefixed1() { let elem: Element = "" .parse().unwrap(); assert_eq!(elem.name(), "features"); assert_eq!(elem.ns(), "http://etherx.jabber.org/streams".to_owned(),); let child = elem.children().next().unwrap(); assert_eq!(child.name(), "message"); assert_eq!(child.ns(), "jabber:client".to_owned()); } #[test] fn namespace_inherited_prefixed2() { let elem: Element = "" .parse().unwrap(); assert_eq!(elem.name(), "stream"); assert_eq!(elem.ns(), "http://etherx.jabber.org/streams".to_owned(),); let child = elem.children().next().unwrap(); assert_eq!(child.name(), "message"); assert_eq!(child.ns(), "jabber:client".to_owned()); } #[test] fn fail_comments() { let elem: Result = "".parse(); match elem { Err(_) => (), _ => panic!(), }; } #[test] fn xml_error() { match "".parse::() { Err(crate::error::Error::XmlError(rxml::Error::ElementMismatch)) => (), err => panic!("No or wrong error: {:?}", err), } match "() { Err(crate::error::Error::XmlError(rxml::Error::InvalidEof(_))) => (), err => panic!("No or wrong error: {:?}", err), } } #[test] fn missing_namespace_error() { match "".parse::() { Err(crate::error::Error::MissingNamespace) => (), err => panic!("No or wrong error: {:?}", err), } } #[test] fn misserialisation() { let xml = "vp9"; //let elem = xml.parse::().unwrap(); let elem = Element::builder("jitsi_participant_codecType", "jabber:client") .append("vp9") .build(); let data = String::from(&elem); assert_eq!(xml, data); } minidom-0.18.0/src/tree_builder.rs000064400000000000000000000151501046102023000151520ustar 00000000000000// Copyright (c) 2022 Astro // Copyright (c) 2025 pep // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //! SAX events to DOM tree conversion use crate::prefixes::{Prefix, Prefixes}; use crate::{Element, Error}; use alloc::string::String; use alloc::vec::Vec; use rxml::{AttrMap, Namespace, RawEvent}; /// Tree-building parser state pub struct TreeBuilder { next_tag: Option<(Prefix, String, Prefixes, AttrMap)>, /// Parsing stack stack: Vec, /// Namespace set stack by prefix prefixes_stack: Vec, attrs_stack: Vec<(String, String, String)>, /// Document root element if finished pub root: Option, } impl Default for TreeBuilder { fn default() -> Self { Self::new() } } impl TreeBuilder { /// Create a new one #[must_use] pub fn new() -> Self { TreeBuilder { next_tag: None, stack: Vec::new(), prefixes_stack: Vec::new(), attrs_stack: Vec::new(), root: None, } } /// Allow setting prefixes stack. /// /// Useful to provide knowledge of namespaces that would have been declared on parent elements /// not present in the reader. #[must_use] pub fn with_prefixes_stack(mut self, prefixes_stack: Vec) -> Self { self.prefixes_stack = prefixes_stack; self } /// Stack depth #[must_use] pub fn depth(&self) -> usize { self.stack.len() } /// Get the top-most element from the stack but don't remove it #[must_use] pub fn top(&mut self) -> Option<&Element> { self.stack.last() } /// Pop the top-most element from the stack fn pop(&mut self) -> Option { self.prefixes_stack.pop(); self.stack.pop() } /// Unshift the first child of the top element pub fn unshift_child(&mut self) -> Option { let depth = self.stack.len(); if depth > 0 { self.stack[depth - 1].unshift_child() } else { None } } /// Lookup XML namespace declaration for given prefix (or no prefix) #[must_use] fn lookup_prefix<'a>( prefixes_stack: &'a Vec, prefix: &'a Option, ) -> Option<&'a str> { for nss in prefixes_stack.iter().rev() { if let Some(ns) = nss.get(prefix) { return Some(ns); } } None } fn process_end_tag(&mut self) { if let Some(el) = self.pop() { if self.depth() > 0 { let top = self.stack.len() - 1; self.stack[top].append_child(el); } else { self.root = Some(el); } } } fn process_text(&mut self, text: String) { if self.depth() > 0 { let top = self.stack.len() - 1; self.stack[top].append_text(text); } } /// Process an event that you got out of a `RawParser`. pub fn process_event(&mut self, event: RawEvent) -> Result<(), Error> { match event { RawEvent::XmlDeclaration(_, _) => {} RawEvent::ElementHeadOpen(_, (prefix, name)) => { // If self.prefixes_stack has been set via with_prefixes_stack before processing, // ensure these are set on the root element. let prefixes = if self.stack.is_empty() && self.prefixes_stack.len() == 1 { self.prefixes_stack.pop().unwrap() } else { Prefixes::default() }; self.next_tag = Some(( prefix.map(|prefix| prefix.as_str().to_owned()), name.as_str().to_owned(), prefixes, AttrMap::new(), )); } RawEvent::Attribute(_, (prefix, name), value) => { if let Some((_, _, ref mut prefixes, ref mut attrs)) = self.next_tag.as_mut() { match (prefix, name) { (None, xmlns) if xmlns == "xmlns" => prefixes.insert(None, value), (Some(xmlns), prefix) if xmlns.as_str() == "xmlns" => { prefixes.insert(Some(prefix.as_str().to_owned()), value); } (Some(prefix), name) => { self.attrs_stack .push((prefix.to_string(), name.to_string(), value)); } (None, name) => { attrs.insert( Namespace::NONE, name.try_into().unwrap(), value.as_str().to_owned(), ); } } } } RawEvent::ElementHeadClose(_) => { if let Some((prefix, name, prefixes, mut attrs)) = self.next_tag.take() { self.prefixes_stack.push(prefixes.clone()); let namespace = TreeBuilder::lookup_prefix( &self.prefixes_stack, &prefix.map(|prefix| prefix.as_str().to_owned()), ) .ok_or(Error::MissingNamespace)? .to_owned(); for (prefix, attr, value) in self.attrs_stack.drain(..) { let ns = if prefix == "xml" { rxml::Namespace::xml() } else { &TreeBuilder::lookup_prefix( &self.prefixes_stack, &Some(prefix.to_string()), ) .map(String::from) .map(|s| TryInto::::try_into(s).unwrap()) .ok_or(Error::MissingNamespace)? .to_owned() }; attrs.insert(ns.clone(), attr.try_into().unwrap(), value.to_string()); } let el = Element::new(name.to_owned(), namespace, prefixes, attrs, Vec::new()); self.stack.push(el); } } RawEvent::ElementFoot(_) => self.process_end_tag(), RawEvent::Text(_, text) => self.process_text(text.as_str().to_owned()), } Ok(()) } }