基于XQuery实现十六进制字符串转ASCII的技术求助
Got it! Converting a hex string to ASCII in XQuery is totally doable—here’s a solid implementation with explanations to help you out:
Hex to ASCII Conversion in XQuery
Core Implementation (XQuery 3.0+)
Here's a concise, readable function using arrow expressions:
declare function local:hex-to-ascii($hex as xs:string) as xs:string { // Validate input has even length (each ASCII char needs 2 hex digits) if (string-length($hex) mod 2 != 0) then error(xs:QName('invalid-hex'), "Hex string must have an even number of characters") else string-to-codepoints($hex) => every-n(2) // Split input into 2-character hex pairs => map(xs:integer(concat('0x', .))) // Convert each pair to decimal ASCII code point => map(xs:char(.)) // Turn decimal code into actual ASCII character => string-join('') // Combine characters into a single string };
Step-by-Step Breakdown
- Input Check: We first make sure the hex string length is even—since every ASCII character maps to exactly two hex digits. If not, we throw a clear error to avoid broken conversions.
- Split into Pairs:
string-to-codepointsbreaks the input into individual character code points, thenevery-n(2)groups them into the 2-digit hex pairs we need. - Hex to Decimal: Adding the
0xprefix tellsxs:integerto treat the pair as a hexadecimal value, converting it to the decimal code point for the corresponding ASCII character. - Decimal to Character:
xs:chartakes the decimal code and returns the actual ASCII character. - Combine Results: Finally, we stitch all the characters together into a single readable string.
Example Usage
Test the function with a sample hex string:
let $sample-hex := "48656C6C6F20576F726C64" // Hex equivalent of "Hello World" return local:hex-to-ascii($sample-hex)
This will output:
Hello World
Compatibility for XQuery 1.0
If you’re working with an older XQuery version that doesn’t support arrow functions, use this FLWOR-based implementation instead:
declare function local:hex-to-ascii($hex as xs:string) as xs:string { if (string-length($hex) mod 2 != 0) then error(xs:QName('invalid-hex'), "Hex string must have an even number of characters") else string-join( for $char in string-to-codepoints($hex) group by $group-id = (position() - 1) idiv 2 let $hex-pair := string-join($char, '') let $code-point := xs:integer(concat('0x', $hex-pair)) return xs:char($code-point), '' ) };
This uses grouping to create hex pairs, achieving the same result without arrow syntax.
内容的提问来源于stack exchange,提问作者Raghu Dacha
相关产品推荐
相关产品推荐

