How to parse html text having singleton tag?
8 ビュー (過去 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 日
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!