0

I have an Html doc that looks like this

<!--?xml version="1.0" encoding="utf-8" ?-->
 <html>
 <head> 
 <meta charset="utf-8"> 
 <title>MyPage</title> 
 <link rel="stylesheet" href="css/epubs.css" type="text/css"> 
</head> 
 <body dir="ltr" xml:lang="zh-cn" class="MyCss">
       --- content 
 </body>
</html>

Using swift soup i'm trying wrap the body in a container tag like this

  <div class="container">
    <body>
    </body>
  </div>

According to the github example this is how you wrap it:

let span: Element = try doc.select("span").first()! // <span>One</span>
try span.wrap("<li><a href='http://example.com/'></a></li>")
print(doc)
// now: <li><a href="http://example.com/"><span>One</span></a></li>

My Code to wrap:

let html = try! String(contentsOf: chaptherFilePath)
let soup:Document = try! SwiftSoup.parse(html)
let soupBody:Element = try! soup.select("body").first()!
try! soupBody.wrap("<div class='container'></div>")

But when I do this it doesn't wrap it around the body it does this weird thing and appends it at the bottom with a new body tag and the div inside that body tag. Not sure why.

<!--?xml version="1.0" encoding="utf-8" ?-->
<html>
 <head> 
  <meta charset="utf-8"> 
  <title>MyPage</title> 
  <link rel="stylesheet" href="css/epubs.css" type="text/css"> 
 </head> 
 <head>
<body dir="ltr" xml:lang="zh-cn" class="MyCss">
      -- Body Content 
</body>
<body>
<div class="container"></div> --- Not sure why it's doing this 
</body>
</head>
4

1 回答 1

0

不确定这是否是一个错误或者我的文档的布局方式,但我让它工作的唯一方法就是这样做。我无法做到这一点wrap如果有人知道为什么包装不起作用我想知道答案。但目前这行得通。

   let html = try! String(contentsOf: chaptherFilePath)
   let soup:Document = try! SwiftSoup.parse(html)
   let soupBody:Elements = try! soup.select("body")
    try! soup.select("body").html("<div class='container'>\(soupBody.html())</div>")
于 2022-01-11T20:28:25.283 回答