Use clear_comments to remove the note above port and the note beside it, while keeping port: 443.
cargo add oneyamlRequires Rust 1.85 or later.
use oneyaml::Document; fn main() { let yaml = "# Old note\nport: 443 # TLS\n"; let mut doc = Document::parse(yaml) .expect("valid YAML"); let mut port = doc.get_mut("port") .expect("port"); let removed = port.clear_comments() .expect("clear comments"); print!("{doc}"); println!("Removed: {removed:?}"); }
Unzip the example, then cargo run.
cargo run prints:
port: 443 Removed: ["# Old note", "# TLS"]
Variations
To remove only the same-line note, replace everything after the let mut port statement with this code. It prints # Old note above port: 443.
port.set_trailing(None) .expect("remove inline note"); print!("{doc}");
Related recipes
The short answer
Parse the YAML as a Document, select the entry with get_mut, and call clear_comments. It edits the YAML and returns the removed comment strings. The example prints the remaining YAML first, then the removed text, including the # markers.
How do you remove YAML comments without deleting the key?
Call clear_comments, not Document::remove_node, which removes the mapping entry. The key and value stay in place. Document::clear_comments takes a node ID and acts on exactly that node. The mutable entry handle used in the example also clears comments owned by the value itself. For example, if the value is a list, the handle can clear the list’s footer as well as the notes on the key.
Neither method walks down into all child entries to strip their comments. If you choose one key in a larger mapping, it isn’t a request to erase the notes on other keys or the document’s header and footer. If the edit would make another comment belong to a different node, it returns EditError::CommentReattaches and changes nothing.
How do you remove an inline YAML comment but keep the note above it?
Use set_trailing(None), as in the variation. A same-line comment is called a trailing comment in the API. This operation targets that slot, so the leading note remains. To do the opposite, use set_leading with NO_COMMENTS.
Avoid deleting everything after a # by string replacement. For instance, in color: "#0055aa", the # is inside a quoted value, not a YAML comment. Editing the selected entry’s parsed comments leaves that value alone.