简体   繁体   English

从 XML 中的 html 格式字符串资源中设置 TextView 文本

[英]Set TextView text from html-formatted string resource in XML

I have some fixed strings inside my strings.xml , something like:我的strings.xml中有一些固定字符串,例如:

<resources>
    <string name="somestring">
        <B>Title</B><BR/>
        Content
    </string>
</resources>

and in my layout I've got a TextView which I'd like to fill with the html-formatted string.在我的布局中,我有一个TextView ,我想用 html 格式的字符串填充它。

<TextView android:id="@+id/formattedtext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/htmlstring"/>

if I do this, the content of formattedtext is just the content of somestring stripped of any html tags and thus unformatted.如果我这样做, formattedtext文本的内容只是剥离任何 html 标签的somestring的内容,因此未格式化。

I know that it is possible to set the formatted text programmatically with我知道可以通过编程方式设置格式化文本

.setText(Html.fromHtml(somestring));

because I use this in other parts of my program where it is working as expected.因为我在我的程序的其他部分使用它,它按预期工作。

To call this function I need an Activity , but at the moment my layout is just a simple more or less static view in plain XML and I'd prefer to leave it that way, to save me from the overhead of creating an Activity just to set some text.要调用这个 function 我需要一个Activity ,但目前我的布局只是一个简单的或多或少的 static 视图在普通 XML 中,我宁愿保持这种状态,以避免我创建Activity的开销只是为了设置一些文本。

Am I overlooking something obvious?我是否忽略了一些明显的东西? Is it not possible at all?难道根本不可能吗? Any help or workarounds welcome!欢迎任何帮助或解决方法!

Edit: Just tried some things and it seems that HTML formatting in xml has some restraints:编辑:刚刚尝试了一些事情,似乎 xml 中的 HTML 格式有一些限制:

  • tags must be written lowercase标签必须小写

  • some tags which are mentioned here do not work, eg <br/> (it's possible to use \n instead) 这里提到的一些标签不起作用,例如<br/> (可以使用\n代替)

Just in case anybody finds this, there's a nicer alternative that's not documented (I tripped over it after searching for hours, and finally found it in the bug list for the Android SDK itself). 万一有人发现这个,有一个更好的替代品没有记录(我搜索了几个小时后绊倒了它,最后在Android SDK本身的bug列表中找到它)。 You CAN include raw HTML in strings.xml, as long as you wrap it in 可以在strings.xml中原始的HTML,只要你把它包装

<![CDATA[ ...raw html... ]]>

Example: 例:

<string name="nice_html">
<![CDATA[
<p>This is a html-formatted string with <b>bold</b> and <i>italic</i> text</p>
<p>This is another paragraph of the same string.</p>
]]>
</string>

Then, in your code: 然后,在您的代码中:

TextView foo = (TextView)findViewById(R.id.foo);
foo.setText(Html.fromHtml(getString(R.string.nice_html)));

IMHO, this is several orders of magnitude nicer to work with :-) 恕我直言,这是几个数量级更好的工作:-)

As the top answer here is suggesting something wrong (or at least too complicated), I feel this should be updated, although the question is quite old: 由于这里的最佳答案是暗示出错 (或者至少过于复杂),我觉得应该更新,尽管问题已经很久了:

When using String resources in Android, you just have to call getString(...) from Java code or use android:text="@string/..." in your layout XML. 在Android中使用String资源时,您只需从Java代码调用getString(...)或在布局XML中使用android:text="@string/..."

Even if you want to use HTML markup in your Strings, you don't have to change a lot: 即使您想在字符串中使用HTML标记,也不必进行大量更改:

The only characters that you need to escape in your String resources are: 您需要在String资源中转义的唯一字符是:

  • double quotation mark: " becomes \\" 双引号: "变成\\"
  • single quotation mark: ' becomes \\' 单引号: '变成\\'
  • ampersand: & becomes &#38; &符号: &变成&#38; or &amp; 或者&amp;

That means you can add your HTML markup without escaping the tags: 这意味着您可以添加HTML标记而无需转义标记:

<string name="my_string"><b>Hello World!</b> This is an example.</string>

However, to be sure, you should only use <b> , <i> and <u> as they are listed in the documentation. 但是,可以肯定的是,您应该只使用文档中列出的<b><i><u>

If you want to use your HTML strings from XML , just keep on using android:text="@string/..." , it will work fine. 如果你想使用XML中的HTML字符串,继续使用android:text="@string/..." ,它将正常工作。

The only difference is that, if you want to use your HTML strings from Java code , you have to use getText(...) instead of getString(...) now, as the former keeps the style and the latter will just strip it off. 唯一的区别是,如果你想使用Java代码中的 HTML字符串,你现在必须使用getText(...)而不是getString(...) ,因为前者保留了样式而后者只是剥离它关了。

It's as easy as that. 就这么简单。 No CDATA, no Html.fromHtml(...) . 没有CDATA,没有Html.fromHtml(...)

You will only need Html.fromHtml(...) if you did encode your special characters in HTML markup. 您只需要Html.fromHtml(...)如果你没有编码的HTML标记的特殊字符。 Use it with getString(...) then. 然后将它与getString(...)一起使用。 This can be necessary if you want to pass the String to String.format(...) . 如果要将String传递给String.format(...)则可能需String.format(...)

This is all described in the docs as well. 这些都在文档中描述。

Edit: 编辑:

There is no difference between getText(...) with unescaped HTML (as I've proposed) or CDATA sections and Html.fromHtml(...) . getText(...)与未转义的HTML(正如我所提议的)或CDATA部分和Html.fromHtml(...)之间没有区别。

See the following graphic for a comparison: 请参阅以下图表以进行比较:

在此输入图像描述

Escape your HTML tags ... 转义HTML标记...

<resources>
    <string name="somestring">
        &lt;B&gt;Title&lt;/B&gt;&lt;BR/&gt;
        Content
    </string>
</resources>

Android does not have a specification to indicate the type of resource string (eg text/plain or text/html). Android没有指定资源字符串类型的规范(例如text / plain或text / html)。 There is a workaround, however, that will allow the developer to specify this within the XML file. 但是,有一种解决方法可以让开发人员在XML文件中指定它。

  1. Define a custom attribute to specify that the android:text attribute is html. 定义自定义属性以指定android:text属性为html。
  2. Use a subclassed TextView. 使用子类TextView。

Once you define these, you can express yourself with HTML in xml files without ever having to call setText(Html.fromHtml(...)) again. 一旦定义了这些,就可以用xml文件中的HTML表达自己,而无需再次调用setText(Html.fromHtml(...))。 I'm rather surprised that this approach is not part of the API. 我很惊讶这种方法不是API的一部分。

This solution works to the degree that the Android studio simulator will display the text as rendered HTML. 此解决方案适用于Android工作室模拟器将文本显示为呈现HTML的程度。

在此输入图像描述

res/values/strings.xml (the string resource as HTML) res / values / strings.xml(字符串资源为HTML)

<resources>
<string name="app_name">TextViewEx</string>
<string name="string_with_html"><![CDATA[
       <em>Hello</em> <strong>World</strong>!
 ]]></string>
</resources>

layout.xml (only the relevant parts) layout.xml(只有相关部分)

Declare the custom attribute namespace, and add the android_ex:isHtml attribute. 声明自定义属性命名空间,并添加android_ex:isHtml属性。 Also use the subclass of TextView. 还可以使用TextView的子类。

<RelativeLayout
...
xmlns:android_ex="http://schemas.android.com/apk/res-auto"
...>

<tv.twelvetone.samples.textviewex.TextViewEx
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/string_with_html"
    android_ex:isHtml="true"
    />
 </RelativeLayout>

res/values/attrs.xml (define the custom attributes for the subclass) res / values / attrs.xml(定义子类的自定义属性)

 <resources>
<declare-styleable name="TextViewEx">
    <attr name="isHtml" format="boolean"/>
    <attr name="android:text" />
</declare-styleable>
</resources>

TextViewEx.java (the subclass of TextView) TextViewEx.java(TextView的子类)

 package tv.twelvetone.samples.textviewex;

 import android.content.Context;
 import android.content.res.TypedArray;
 import android.support.annotation.Nullable;
 import android.text.Html;
 import android.util.AttributeSet;
 import android.widget.TextView;

public TextViewEx(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TextViewEx, 0, 0);
    try {
        boolean isHtml = a.getBoolean(R.styleable.TextViewEx_isHtml, false);
        if (isHtml) {
            String text = a.getString(R.styleable.TextViewEx_android_text);
            if (text != null) {
                setText(Html.fromHtml(text));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        a.recycle();
    }
}
}

Latest update: 最近更新:

Html.fromHtml(string); //deprecated after Android N versions.. //在Android N版本之后弃用..

Following code give support to android N and above versions... 以下代码支持android N及以上版本...

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
textView.setText(Html.fromHtml(yourHtmlString,Html.FROM_HTML_MODE_LEGACY));
}

else 
{
textView.setText(Html.fromHtml(yourHtmlString));
}
  String termsOfCondition="<font color=#cc0029>Terms of Use </font>";
  String commma="<font color=#000000>, </font>";
  String privacyPolicy="<font color=#cc0029>Privacy Policy </font>";
  Spanned text=Html.fromHtml("I am of legal age and I have read, understood, agreed and accepted the "+termsOfCondition+commma+privacyPolicy);
        secondCheckBox.setText(text);

I have another case when I have no chance to put CDATA into the xml as I receive the string HTML from a server. 我有另一种情况,当我从服务器收到字符串HTML时,我没有机会将CDATA放入xml。

Here is what I get from a server: 这是我从服务器得到的:

<p>The quick brown&nbsp;<br />
fox jumps&nbsp;<br />
 over the lazy dog<br />
</p>

It seems to be more complicated but the solution is much simpler. 它似乎更复杂,但解决方案更简单。

private TextView textView;

protected void onCreate(Bundle savedInstanceState) { 
.....
textView = (TextView) findViewById(R.id.text); //need to define in your layout
String htmlFromServer = getHTMLContentFromAServer(); 
textView.setText(Html.fromHtml(htmlFromServer).toString());

}

Hope it helps! 希望能帮助到你!
Linh

If you want to show html scrip in android app Like TextView如果你想在 android 应用程序中显示 html 股票 喜欢 TextView

Please follow this code请遵循此代码

Kotlin

var stringvalue = "Your Sting"

yourTextVew.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Html.fromHtml(stringvalue, Html.FROM_HTML_MODE_COMPACT)
        } else {
            Html.fromHtml(stringvalue)
        }

Java

String stringvalue = "Your String";

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                   yourTextVew.setText(Html.fromHtml(stringvalue, Html.FROM_HTML_MODE_COMPACT))
                } else {
                   yourTextVew.setText( Html.fromHtml(stringvalue))
                }

转换无序列表 (<ul> ) 转换为 HTML 格式的表格 (<div id="text_translate"><p> 我以前一直在寻求一种解决方案,允许我将无序列表转换为格式化的 HTML 表。</p><p> 当时,一位好心的用户提出了一个解决方案,我在下面附上了。</p><p> 该解决方案将无序列表转变为 Google 表格中的常规表格,其中不同的值被划分到它们自己的单元格中。 相反,我希望将无序列表转换为仅放在一个单元格中的格式化 html 表列表。</p><p> 如果可能的话,除此之外,我希望能够将数百个无序列表放入脚本中,然后将其转换为各自的 HTML 格式的表格。</p><p> 请参阅下面我从另一个用户那里获得的先前解决方案。</p><p> 希望这一切都有意义。</p><p> <strong>编辑:</strong>我还在这篇文章的最底部添加了输入和首选 output。</p><pre> In your situation, how about the following sample script? Sample script 1: This script parses your value using the regex. function myFunction1() { // This sample value is from your question. const sample = `<ul> <li>Material: 100% polyester with polyurethane coating</li> <li>Water column pressure: 4000mm</li> <li>Fit: Regular unisex</li> <li>Elasticated waistband with drawstring</li> <li>Elasticated cuffs with tonal coated zips</li> <li>Single back pocket with eyelet</li> <li>Concealed side pockets</li> <li>Ultrasonically welded seams</li> <li>Reflective accents</li> </ul>`; // Parse list. const obj = sample.matchAll(/<li>([\w\S\s]+?)<\/li>/g); const values = [...obj].map(e => { if (e && e.length > 1) { const temp = e[1].split(":"); return temp.length == 1? [temp[0].trim(), ""]: temp.map(f => f.trim()); } return ["", ""]; }); // Put the values to the sheet. const sheetName = "Sheet1"; // Please set the sheet name. const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName); sheet.getRange(1, 1, values.length, values[0].length).setValues(values); } When this script is run, your sample value is parsed. And, the values are put to the sheet. Sample script 2: This script parses your value using XmlService. function myFunction1() { // This sample value is from your question. const sample = `<ul> <li>Material: 100% polyester with polyurethane coating</li> <li>Water column pressure: 4000mm</li> <li>Fit: Regular unisex</li> <li>Elasticated waistband with drawstring</li> <li>Elasticated cuffs with tonal coated zips</li> <li>Single back pocket with eyelet</li> <li>Concealed side pockets</li> <li>Ultrasonically welded seams</li> <li>Reflective accents</li> </ul>`; // Parse list. const root = XmlService.parse(sample).getRootElement(); const values = root.getChildren("li", root.getNamespace()).map(e => { const temp = e.getValue().split(":"); return temp.length == 1? [temp[0].trim(), ""]: temp.map(f => f.trim()); }); // Put the values to the sheet. const sheetName = "Sheet1"; // Please set the sheet name. const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName); sheet.getRange(1, 1, values.length, values[0].length).setValues(values); } References: map() setValues(values) Added: From your following additional question, That does the job for doing it on one single product. Let's say I have a batch of product details for several different products. Like here below. Is there a way to run the script on all three at once so it becomes three different tables? In this case, how about the following sample script? Sample script: function myFunction2() { // This is from your new question. const samples = [ "<ul><li>Material: 100% polyester with polyurethane coating</li><li>Lining: 100% polyester</li><li>Insulation: 100% polyester</li><li>Measurements: H160cm x W140cm x D1cm / H63 x W55.1 x 0.4 inches</li><li>When packed: H13cm x W47cm x D25cm / H5.1 x W18.5 x D9.8 inc </li><li>Pack-carry-store system with buckles and adjustable webbing straps</li><li>Soft, quilted and padded side</li><li>Waterproof upper on reverse</li></ul>", "<ul><li>Material: 100% polyester with polyurethane coating</li><li>Water column pressure: 4000mm</li><li>Soft mesh lining</li><li>Circumference: S1 – 61.5 cm / 24.2 inches, / S2 - 66 cm / 26 inches</li></ul>", "<ul><li>Material: 100% polyester with polyurethane coating</li><li>Lining: 100% polyester </li><li>Water column pressure: 8000mm</li><li>Measurements: H16 x W21 x D8.5cm / H6.3 x W8.3 x D3.3 inches</li><li>Volume: 3 liters / 0.8 gallons</li><li>Coated tonal zip closure</li><li>Single main compartment </li><li>Detachable adjustable webbing shoulder strap </li><li>Carry handle</li></ul>" ]; const sheetNames = ["Sheet1", "Sheet2", "Sheet3"]; // Please set the sheet names. samples.forEach((sample, i) => { const root = XmlService.parse(sample).getRootElement(); const values = root.getChildren("li", root.getNamespace()).map(e => { const temp = e.getValue().split(":"); return temp.length == 1? [temp[0].trim(), ""]: temp.map(f => f.trim()); }); const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetNames[i]); sheet.getRange(1, 1, values.length, values[0].length).setValues(values); }); }</pre><p> 请参阅下面的输入和首选 output。</p><p> 每当有一行带有冒号的文本时,比如“材料:100% 聚酯与聚氨酯涂层”,我希望它在表中分成两列,这样“材料:”在第 1 列,“带聚氨酯涂层的 100% 聚酯”在第 2 栏中。</p><p> <strong>输入:</strong></p><pre> /** List 1 **/ <ul> <li>Material: 100% polyester with polyurethane coating</li> <li>Lining: 100% polyester</li> <li>Insulation: 100% polyester</li> <li>Measurements: H160cm x W140cm x D1cm / H63 x W55.1 x 0.4 inches</li> <li>When packed: H13cm x W47cm x D25cm / H5.1 x W18.5 x D9.8 inc </li> <li>Pack-carry-store system with buckles and adjustable webbing straps</li> <li>Soft, quilted and padded side</li> <li>Waterproof upper on reverse</li> </ul> /** List 2 **/ <ul> <li>Material: 100% polyester with polyurethane coating</li> <li>Water column pressure: 4000mm</li> <li>Circumference: S1 – 61.5 cm / 24.2 inches, / S2 - 66 cm / 26 inches</li> <li>Soft mesh lining</li> </ul> /** List 3 **/ <ul> <li>Material: 100% polyester with polyurethane coating</li> <li>Lining: 100% polyester </li> <li>Water column pressure: 8000mm</li> <li>Measurements: H16 x W21 x D8.5cm / H6.3 x W8.3 x D3.3 inches</li> <li>Volume: 3 liters / 0.8 gallons</li> <li>Coated tonal zip closure</li> <li>Single main compartment </li> <li>Detachable adjustable webbing shoulder strap </li> <li>Carry handle</li> </ul></pre><p> <strong>通缉output:</strong></p><pre> /** Table 1 (converted from List 1) **/ <table> <tbody> <tr> <td>Material:</td> <td>100% polyester with polyurethane coating</td> </tr> <tr> <td>Lining:</td> <td>100% polyester</td> </tr> <tr> <td>Insulation:</td> <td>100% polyester</td> </tr> <tr> <td>Measurements:</td> <td>H160cm x W140cm x D1cm / H63 x W55.1 x 0.4 inches</td> </tr> <tr> <td>When packed:</td> <td>H13cm x W47cm x D25cm / H5.1 x W18.5 x D9.8 inc</td> </tr> <tr> <td>Pack-carry-store system with buckles and adjustable webbing straps</td> <td></td> </tr> <tr> <td>Soft, quilted and padded side</td> <td></td> </tr> <tr> <td>Waterproof upper on reverse</td> <td></td> </tr> </tbody> </table> /** Table 2 (converted from List 2) **/ <table> <tbody> <tr> <td>Material:</td> <td>100% polyester with polyurethane coating</td> </tr> <tr> <td>Water column pressure:</td> <td>4000mm</td> </tr> <tr> <td>Circumference:</td> <td>S1 – 61.5 cm / 24.2 inches, / S2 - 66 cm / 26 inches</td> </tr> <tr> <td>Soft mesh lining</td> <td></td> </tr> </tbody> </table> /** Table 3 (converted from List 3) **/ <table> <tbody> <tr> <td>Material:</td> <td>100% polyester with polyurethane coating</td> </tr> <tr> <td>Lining:</td> <td>100% polyester</td> </tr> <tr> <td>Water column pressure:</td> <td>8000mm</td> </tr> <tr> <td>Measurements:</td> <td>H16 x W21 x D8.5cm / H6.3 x W8.3 x D3.3 inches</td> </tr> <tr> <td>Volume:</td> <td>3 liters / 0.8 gallons</td> </tr> <tr> <td>Coated tonal zip closure</td> <td></td> </tr> <tr> <td>Single main compartment</td> <td></td> </tr> <tr> <td>Detachable adjustable webbing shoulder strap</td> <td></td> </tr> <tr> <td>Carry handle</td> <td></td> </tr> </tbody> </table></pre></div>)<table> </table></ul> - Convert unordered lists (<ul>) into HTML-formatted tables (<table>)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将 html 格式的文本保存到数据库 - save html-formatted text to database 在Android TextView中插入HTML格式的字符串(不是资源) - Inserting HTML formatted (not a resource) string in android TextView 如何将HTML格式的String解析为纯字符串? - How to parse HTML-formatted String to plain string? 是否有一个XmlWriter可以编写色彩鲜艳的HTML格式的输出以在网页中显示XML? - Is there an XmlWriter that writes a colorful HTML-formatted output for displaying XML in a webpage? Android:加快(html格式)文本的显示 - Android: Speeding up display of (html-formatted) text C#将HTML格式的表复制到剪贴板 - C# Copy HTML-formatted table to clipboard 我应该避免使用HTML格式的通知电子邮件吗? - Should I avoid HTML-formatted notification e-mails? 转换无序列表 (<ul> ) 转换为 HTML 格式的表格 (<div id="text_translate"><p> 我以前一直在寻求一种解决方案,允许我将无序列表转换为格式化的 HTML 表。</p><p> 当时,一位好心的用户提出了一个解决方案,我在下面附上了。</p><p> 该解决方案将无序列表转变为 Google 表格中的常规表格,其中不同的值被划分到它们自己的单元格中。 相反,我希望将无序列表转换为仅放在一个单元格中的格式化 html 表列表。</p><p> 如果可能的话,除此之外,我希望能够将数百个无序列表放入脚本中,然后将其转换为各自的 HTML 格式的表格。</p><p> 请参阅下面我从另一个用户那里获得的先前解决方案。</p><p> 希望这一切都有意义。</p><p> <strong>编辑:</strong>我还在这篇文章的最底部添加了输入和首选 output。</p><pre> In your situation, how about the following sample script? Sample script 1: This script parses your value using the regex. function myFunction1() { // This sample value is from your question. const sample = `<ul> <li>Material: 100% polyester with polyurethane coating</li> <li>Water column pressure: 4000mm</li> <li>Fit: Regular unisex</li> <li>Elasticated waistband with drawstring</li> <li>Elasticated cuffs with tonal coated zips</li> <li>Single back pocket with eyelet</li> <li>Concealed side pockets</li> <li>Ultrasonically welded seams</li> <li>Reflective accents</li> </ul>`; // Parse list. const obj = sample.matchAll(/<li>([\w\S\s]+?)<\/li>/g); const values = [...obj].map(e => { if (e && e.length > 1) { const temp = e[1].split(":"); return temp.length == 1? [temp[0].trim(), ""]: temp.map(f => f.trim()); } return ["", ""]; }); // Put the values to the sheet. const sheetName = "Sheet1"; // Please set the sheet name. const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName); sheet.getRange(1, 1, values.length, values[0].length).setValues(values); } When this script is run, your sample value is parsed. And, the values are put to the sheet. Sample script 2: This script parses your value using XmlService. function myFunction1() { // This sample value is from your question. const sample = `<ul> <li>Material: 100% polyester with polyurethane coating</li> <li>Water column pressure: 4000mm</li> <li>Fit: Regular unisex</li> <li>Elasticated waistband with drawstring</li> <li>Elasticated cuffs with tonal coated zips</li> <li>Single back pocket with eyelet</li> <li>Concealed side pockets</li> <li>Ultrasonically welded seams</li> <li>Reflective accents</li> </ul>`; // Parse list. const root = XmlService.parse(sample).getRootElement(); const values = root.getChildren("li", root.getNamespace()).map(e => { const temp = e.getValue().split(":"); return temp.length == 1? [temp[0].trim(), ""]: temp.map(f => f.trim()); }); // Put the values to the sheet. const sheetName = "Sheet1"; // Please set the sheet name. const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName); sheet.getRange(1, 1, values.length, values[0].length).setValues(values); } References: map() setValues(values) Added: From your following additional question, That does the job for doing it on one single product. Let's say I have a batch of product details for several different products. Like here below. Is there a way to run the script on all three at once so it becomes three different tables? In this case, how about the following sample script? Sample script: function myFunction2() { // This is from your new question. const samples = [ "<ul><li>Material: 100% polyester with polyurethane coating</li><li>Lining: 100% polyester</li><li>Insulation: 100% polyester</li><li>Measurements: H160cm x W140cm x D1cm / H63 x W55.1 x 0.4 inches</li><li>When packed: H13cm x W47cm x D25cm / H5.1 x W18.5 x D9.8 inc </li><li>Pack-carry-store system with buckles and adjustable webbing straps</li><li>Soft, quilted and padded side</li><li>Waterproof upper on reverse</li></ul>", "<ul><li>Material: 100% polyester with polyurethane coating</li><li>Water column pressure: 4000mm</li><li>Soft mesh lining</li><li>Circumference: S1 – 61.5 cm / 24.2 inches, / S2 - 66 cm / 26 inches</li></ul>", "<ul><li>Material: 100% polyester with polyurethane coating</li><li>Lining: 100% polyester </li><li>Water column pressure: 8000mm</li><li>Measurements: H16 x W21 x D8.5cm / H6.3 x W8.3 x D3.3 inches</li><li>Volume: 3 liters / 0.8 gallons</li><li>Coated tonal zip closure</li><li>Single main compartment </li><li>Detachable adjustable webbing shoulder strap </li><li>Carry handle</li></ul>" ]; const sheetNames = ["Sheet1", "Sheet2", "Sheet3"]; // Please set the sheet names. samples.forEach((sample, i) => { const root = XmlService.parse(sample).getRootElement(); const values = root.getChildren("li", root.getNamespace()).map(e => { const temp = e.getValue().split(":"); return temp.length == 1? [temp[0].trim(), ""]: temp.map(f => f.trim()); }); const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetNames[i]); sheet.getRange(1, 1, values.length, values[0].length).setValues(values); }); }</pre><p> 请参阅下面的输入和首选 output。</p><p> 每当有一行带有冒号的文本时,比如“材料:100% 聚酯与聚氨酯涂层”,我希望它在表中分成两列,这样“材料:”在第 1 列,“带聚氨酯涂层的 100% 聚酯”在第 2 栏中。</p><p> <strong>输入:</strong></p><pre> /** List 1 **/ <ul> <li>Material: 100% polyester with polyurethane coating</li> <li>Lining: 100% polyester</li> <li>Insulation: 100% polyester</li> <li>Measurements: H160cm x W140cm x D1cm / H63 x W55.1 x 0.4 inches</li> <li>When packed: H13cm x W47cm x D25cm / H5.1 x W18.5 x D9.8 inc </li> <li>Pack-carry-store system with buckles and adjustable webbing straps</li> <li>Soft, quilted and padded side</li> <li>Waterproof upper on reverse</li> </ul> /** List 2 **/ <ul> <li>Material: 100% polyester with polyurethane coating</li> <li>Water column pressure: 4000mm</li> <li>Circumference: S1 – 61.5 cm / 24.2 inches, / S2 - 66 cm / 26 inches</li> <li>Soft mesh lining</li> </ul> /** List 3 **/ <ul> <li>Material: 100% polyester with polyurethane coating</li> <li>Lining: 100% polyester </li> <li>Water column pressure: 8000mm</li> <li>Measurements: H16 x W21 x D8.5cm / H6.3 x W8.3 x D3.3 inches</li> <li>Volume: 3 liters / 0.8 gallons</li> <li>Coated tonal zip closure</li> <li>Single main compartment </li> <li>Detachable adjustable webbing shoulder strap </li> <li>Carry handle</li> </ul></pre><p> <strong>通缉output:</strong></p><pre> /** Table 1 (converted from List 1) **/ <table> <tbody> <tr> <td>Material:</td> <td>100% polyester with polyurethane coating</td> </tr> <tr> <td>Lining:</td> <td>100% polyester</td> </tr> <tr> <td>Insulation:</td> <td>100% polyester</td> </tr> <tr> <td>Measurements:</td> <td>H160cm x W140cm x D1cm / H63 x W55.1 x 0.4 inches</td> </tr> <tr> <td>When packed:</td> <td>H13cm x W47cm x D25cm / H5.1 x W18.5 x D9.8 inc</td> </tr> <tr> <td>Pack-carry-store system with buckles and adjustable webbing straps</td> <td></td> </tr> <tr> <td>Soft, quilted and padded side</td> <td></td> </tr> <tr> <td>Waterproof upper on reverse</td> <td></td> </tr> </tbody> </table> /** Table 2 (converted from List 2) **/ <table> <tbody> <tr> <td>Material:</td> <td>100% polyester with polyurethane coating</td> </tr> <tr> <td>Water column pressure:</td> <td>4000mm</td> </tr> <tr> <td>Circumference:</td> <td>S1 – 61.5 cm / 24.2 inches, / S2 - 66 cm / 26 inches</td> </tr> <tr> <td>Soft mesh lining</td> <td></td> </tr> </tbody> </table> /** Table 3 (converted from List 3) **/ <table> <tbody> <tr> <td>Material:</td> <td>100% polyester with polyurethane coating</td> </tr> <tr> <td>Lining:</td> <td>100% polyester</td> </tr> <tr> <td>Water column pressure:</td> <td>8000mm</td> </tr> <tr> <td>Measurements:</td> <td>H16 x W21 x D8.5cm / H6.3 x W8.3 x D3.3 inches</td> </tr> <tr> <td>Volume:</td> <td>3 liters / 0.8 gallons</td> </tr> <tr> <td>Coated tonal zip closure</td> <td></td> </tr> <tr> <td>Single main compartment</td> <td></td> </tr> <tr> <td>Detachable adjustable webbing shoulder strap</td> <td></td> </tr> <tr> <td>Carry handle</td> <td></td> </tr> </tbody> </table></pre></div>)<table> </table></ul> - Convert unordered lists (<ul>) into HTML-formatted tables (<table>) HTML字符串到Swift中的格式化文本 - HTML string to formatted text in Swift 将Html和Set文本转换为Textview - Convert Html and Set text to Textview
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM