`test.xml`:
```xml
<?xml version="1.0" encoding="UTF-16"?><hierarchy>
<node text="A" />
<node text="B" />
</hierarchy>
```

```bash
cat test.txt | xmlstarlet select --template --value-of '//node/@bounds'
```
```
-:1.38: Blank needed here
㸿格敩慲捲票ਾ†渼摯⁥整瑸∽≁⼠ਾ†渼摯⁥整瑸∽≂⼠
^
-:1.38: parsing XML declaration: '?>' expected
㸿格敩慲捲票ਾ†渼摯⁥整瑸∽≁⼠ਾ†渼摯⁥整瑸∽≂⼠
^
```

What is wrong?
Jul 17, 7:26pm

The issue in your case is related to the encoding mismatch between the XML file and the tool (xmlstarlet) processing it. Here's what's happening:


Root Cause

  1. XML Declaration: Your test.xml file declares its encoding as UTF-16:

    xml
    <?xml version="1.0" encoding="UTF-16"?>

    However, the actual content of the file is likely not encoded in UTF-16. The file appears to be in a different encoding (possibly UTF-8 or ASCII), but the declaration explicitly states UTF-16.

  2. xmlstarlet Behavior:

    • xmlstarlet reads the XML declaration and expects the file to be in UTF-16.
    • If the file is not actually UTF-16, xmlstarlet will fail to parse it, resulting in the error:
      text
      parsing XML declaration: '?>' expected

How to Fix It

Option 1: Change the XML Declaration

If your file is not UTF-16 encoded (e.g., it's UTF-8 or ASCII), update the XML declaration to match the actual encoding:

xml
<?xml version="1.0" encoding="UTF-8"?>

Then save the file as UTF-8.

Option 2: Convert the File to UTF-16

If you want to keep the declaration as UTF-16, ensure the file is actually saved in UTF-16 encoding. You can do this using tools like:

  • iconv (Linux/macOS):
    bash
    iconv -f UTF-8 -t UTF-16 test.xml > test_utf16.xml
  • Text editors (e.g., Notepad++, VS Code) that allow you to save files in specific encodings.

Option 3: Force xmlstarlet to Ignore Encoding

If you are sure the file is UTF-8 but misdeclared, you can preprocess it to remove the encoding attribute or use a tool like recode to fix it.


Testing the Fix

After fixing the encoding, run your command again:

bash
cat test.xml | xmlstarlet sel -t -v '//node/@bounds'

If the file is correctly encoded, this should work without errors.


Jul 17, 7:26pm

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.

Vibe can make mistakes. Check answers. Learn more