Problem with comments in XML files
Mostra commenti meno recenti
I have an m-file that reads an XML file to get inputs. I'm running into a problem with comments in the XML file. Simply put, if I put a comment inside the tag but before the value, then I get an empty string for the value. Comments elsewhere don't cause problems
Here's a toy example of my m-file:
function userInputStruct = readToyXmlInput()
toyXmlInputFile = 'toyXmlInput.xml';
xDoc = xmlread(toyXmlInputFile);
userInput = xDoc.getElementsByTagName('userInput');
userInputStruct = struct(); % Initialize
thisUserInput = userInput.item(0);
thisInput_01 = thisUserInput.getElementsByTagName('input_01');
thisInput_01Element = thisInput_01.item(0);
temp01 = thisInput_01Element.getFirstChild.getData;
temp02 = string(temp01);
input_01 = strip(temp02);
userInputStruct.input_01 = input_01;
Here's a toy example of my XML file:
<toyXmlInput>
<userInput>
<!-- A comment here is fine. -->
<input_01>
Dummy input #1 <!-- A comment here is fine. -->
<!-- A comment here is fine. -->
</input_01>
</userInput>
</toyXmlInput>
Here's a toy example of my XML file with a comment that causes a problem.
<toyXmlInput>
<userInput>
<input_01>
<!-- A comment here causes problems -->
Dummy input #1
</input_01>
</userInput>
</toyXmlInput>
What am I doing wrong? What can I do differently so that comments after the tag but before the value don't cause problems?
Worst-case, I'll just document in the m-file and the XML file that there's a limit on where comments can go. However, I'd prefer a more elegant solution.
Risposta accettata
Più risposte (1)
Do you need the comments to be imported? If not, and if upgrading to release R2020b or later is an option, consider using readstruct to read the contents of the XML file into a struct array. I've attached xmlfile1.txt and xmlfile2.txt as your two toy XML files. [I can't attach the files as .xml.] But I copy them into XML files with the first two lines.
copyfile xmlfile1.txt xmlfile1.xml
copyfile xmlfile2.txt xmlfile2.xml
The comments are not present in the data1 and data2 struct arrays, but the data is present.
data1 = readstruct('xmlfile1.xml')
data1.userInput
data2 = readstruct('xmlfile2.xml')
data2.userInput
Categorie
Scopri di più su Structured Data and XML Documents in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!