XPath and CSS Selectors: Test Expressions Before They Hit Production
When to use XPath vs CSS selectors, how to write stable queries, and a browser-side workflow for testing against real HTML without shipping brittle scrapers.
How to format and inspect XML without breaking namespaces, attributes, or mixed content — plus when to beautify vs minify and how XPath fits the workflow.
By codefunc
XML still powers SOAP APIs, SAML assertions, RSS/Atom, Office Open XML, Android layouts, and countless enterprise configs. Minified or hand-mangled XML is unreadable in review; aggressive "pretty printers" that rewrite namespaces or collapse mixed content can change meaning. Formatting is a readability tool — not a license to normalize away semantics. This guide shows how to beautify XML safely and how to inspect structure with selectors when grepping fails.
Bottom line: Format XML for humans; preserve declaration, namespaces, and attribute values exactly. Use an XML Formatter before review, an HTML Beautifier when the document is HTML-ish, and an XPath / CSS Selector Tester to verify nodes after edits. Never pretty-print a signed XML payload you still need to verify.
| Domain | Examples |
|---|---|
| Identity / auth | SAML, some WS-Security envelopes |
| Feeds / content | RSS, Atom, sitemaps |
| Platform config | Android XML, Maven POM, MSBuild |
| Documents | DOCX/XLSX internals (ZIP of XML) |
| Legacy APIs | SOAP, proprietary XML-RPC-style services |
If you only work in JSON APIs, you will still hit XML in SSO, mobile, or partner integrations. Treat it as first-class when you do.
Safe formatting typically:
Unsafe or risky changes:
| Change | Risk |
|---|---|
| Dropping XML declaration | Consumers may assume encoding/version |
| Rewriting namespace prefixes | Breaks XPath, some signature refs, human mental model |
| Reordering attributes used in signatures | XML canonicalization / C14N sensitivity |
| Trimming whitespace in mixed content | Hello <b>world</b> spacing can matter |
| Entity expansion / resolution | Security and content changes |
| HTML void-element rules on XML | Self-closing vs paired tags differ by vocabulary |
For digitally signed XML (SAML, some payment messages), do not re-serialize before verification. Format a copy for reading; verify against the original bytes.
<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="https://example.com/catalog"
xmlns:meta="https://example.com/meta">
<book id="b1" meta:sku="BOOK-01">
<title>Discrete Math</title>
<price currency="USD">42.00</price>
</book>
</catalog>
After formatting, nesting should make book → title / price obvious. Namespace URIs on xmlns* must remain identical.
Namespaces bind a URI to elements/attributes. Prefixes are local aliases — the URI is the identity.
<a:Order xmlns:a="urn:orders:v1" xmlns:b="urn:billing:v1">
<a:Id>1042</a:Id>
<b:Total>19.99</b:Total>
</a:Order>
| Concept | Meaning |
|---|---|
Prefix (a, b) |
Shortcut in this document |
| Namespace URI | Real identity of the name |
Default xmlns= |
Applies to unprefixed elements in scope |
| Attributes | Unprefixed attributes are in no namespace (usually) |
A formatter that changes a: to ord: is still the same infoset if URIs match — but your XPath and docs may not. Prefer tools that keep prefixes stable.
When searching, prefer namespace-aware XPath (see the companion mental model below) over string search for <Total>, which matches the wrong vocabulary.
Both are common; teams bikeshed. Practical guidance:
| Use attributes for | Use child elements for |
|---|---|
| IDs, flags, simple scalars | Nested structure, repeated values |
| Metadata that qualifies the element | Rich text / mixed content |
| Compact machine config | Extensibility over time |
<!-- Compact -->
<item sku="PEN-03" qty="2" />
<!-- Extensible -->
<item>
<sku>PEN-03</sku>
<qty>2</qty>
<notes>Backorder OK</notes>
</item>
Formatting will not fix a bad model — but indented child elements make extension points obvious in review.
Mixed content = text + elements as siblings:
<p>Use <code>kubectl</code> carefully.</p>
Pretty-printers that insert newlines inside mixed content can alter the string value:
<p>
Use
<code>kubectl</code>
carefully.
</p>
Some applications collapse whitespace; others do not. For prose-like XML (DocBook, XHTML), check rendered or string-value output after formatting. For data-centric XML (no mixed content), indent freely.
| Topic | XML | HTML |
|---|---|---|
| Well-formedness | Required | Browsers recover from many errors |
| Void elements | Explicit (<br/> or paired per schema) |
<br>, <img> rules built-in |
| Namespaces | Central | Rare in HTML5 |
| Case | Case-sensitive | HTML tag names case-insensitive in HTML parser |
If you paste an HTML page into an XML-only parser, unclosed tags and entities can fail. Use HTML Beautifier for HTML documents and XML Formatter for true XML.
Readable XML is step one. Step two is targeting nodes:
//book[@id='b1']/price
book#b1 > price
CSS selectors are often enough for HTML-like trees. XPath is stronger for axes (parent::, following-sibling::), namespaces, and attribute predicates. Validate expressions against a sample document in the XPath / CSS Selector Tester before you bake them into scrapers, tests, or CI asserts.
| Goal | Action |
|---|---|
| Code review / debugging | Beautify |
| Wire size (rare for XML today) | Minify — usually gzip matters more |
| Golden-file tests | Pick one canonical form and stick to it |
| Signed documents | Do not alter |
Prefer consistent indentation (2 spaces) in repos you control so diffs stay small.
| Error symptom | Likely cause | Fix |
|---|---|---|
| "Unexpected token" mid-file | Raw < in text |
Use < or CDATA |
| Encoding mojibake | Declared UTF-8, file is Windows-1252 | Re-save as UTF-8; fix declaration |
| Namespace not bound | Typo in prefix | Align xmlns:prefix |
| Duplicate attribute | Copy-paste | Remove duplicate |
| Content after root | Two root elements | Wrap in a single root |
Format first — many "logic bugs" are truncated documents that become obvious when indentation collapses at the break point.
Format XML to understand structure; do not casually rewrite namespaces, whitespace in mixed content, or any signed payload. Use the XML Formatter for well-formed XML, the HTML Beautifier for HTML documents, and the XPath / CSS Selector Tester to confirm the nodes your code will touch. Preserve the original bytes when verification or signatures matter — pretty-print a copy, edit with intent, and keep CI canonicalization explicit.
When to use XPath vs CSS selectors, how to write stable queries, and a browser-side workflow for testing against real HTML without shipping brittle scrapers.
How to format SQL for code review clarity, where dialects disagree, and when you should not reformat production migrations or generated queries.
A practical GFM workflow for developers — preview Markdown safely, convert HTML when needed, and understand the caveats of Markdown ↔ HTML round-trips.
Find a developer tool