How to parse html text having singleton tag?
23 次查看(过去 30 天)
显示 更早的评论
I have a htmldata stored in the form of char array
<html>
<head>
</head>
<body>
<div class="header">
HEADER1
</div>
<div class="content">
<br>my data
</div>
</body>
</html>
I want to retreive data between tags for which i tried some thing like
import javax.xml.parsers.DocumentBuilderFactory
dbf=javax.xml.parsers.DocumentBuilderFactory.newInstance();
builder = dbf.newDocumentBuilder();
is=org.xml.sax.InputSource(java.io.StringReader(htmldata));
dom=builder.parse(is);
The above code works fine when there are no singleton tags. but it throws error when I add singleton tags [Fatal Error] :36:7: The element type "br" must be terminated by the matching end-tag "</br>".
even xmlread throwns same error
>> xmlread(is)
[Fatal Error] :The element type "br" must be terminated by the matching end-tag "</br>".
Error using xmlread (line 106)
Java exception occurred:
org.xml.sax.SAXParseException; The element type "br" must be terminated by the matching end-tag
"</br>".
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
is there any workaround for this ?
采纳的回答
Arjun
2024-11-5,6:32
Hi @SR,
I see that you want to parse some HTML text containing singleton tags using MATLAB.
The issue arises because you're using an XML parser to process HTML content. XML parsers expect every opened tag to have a corresponding closing tag, which isn't always the case with HTML. HTML allows for self-closing tags that don't require a separate closing tag, leading to errors when parsed with XML tools. To handle HTML properly, you can use “htmlTree” offered by MATLAB R2021b and newer versions.
Kindly refer to the documentation of the “htmlTree” for more information: https://www.mathworks.com/help/releases/R2021b/textanalytics/ref/htmltree.html
Kindly refer to the code snippet below for illustration:
htmlData = [...
'<html>', ...
' <head>', ...
' </head>', ...
' <body>', ...
' <div class="header">', ...
' HEADER1', ...
' </div>', ...
' <div class="content">', ...
' <br>my data', ...
' </div>', ...
' </body>', ...
'</html>'];
htmlString = string(htmlData);
% Parse the HTML content using htmlTree
tree = htmlTree(htmlString);
% Extract content from the header and content divs
headerContent = extractHTMLText(findElement(tree, ".header"));
contentData = extractHTMLText(findElement(tree, ".content"));
disp("Header Content: " + headerContent);
disp("Content Data: " + contentData);
I hope this will help!
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 String Parsing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!