You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中XML字符串转XML对象及添加trust属性问题

How to Convert Escaped XML String to XML Object and Add Trust Attribute

Absolutely, converting that escaped XML string to an XML object is a great solution here—it lets you manipulate the XML structure directly, including adding or modifying the trust attribute, before handling the trusted content in Angular. Let’s walk through how to do this:

Step 1: Unescape and Parse the XML String

First, you’ll need to turn your escaped XML string into a proper XML document object. In browser environments, the native DOMParser works perfectly for this:

// Your escaped XML string (example value)
const escapedXml = "<div class=\"content\"><p>Some escaped content</p></div>";

// Unescape the string to get raw XML markup
const rawXml = unescape(escapedXml);

// Parse the raw XML into a document object
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(rawXml, "text/xml");

Step 2: Add/Modify the trust Attribute

Now that you have an XML object, you can target any element and add the trust attribute just like you would with regular DOM elements:

// Target the element you want to update (adjust the selector to match your XML)
const targetElement = xmlDoc.querySelector("div.content");

// Add the trust attribute with your desired value
targetElement.setAttribute("trust", "trusted");

Step 3: Convert Back to String and Use with Angular’s $sce

Once you’ve updated the XML structure, convert it back to a string and use Angular’s $sce to mark it as trusted HTML:

// Serialize the modified XML object back to a string
const serializer = new XMLSerializer();
const modifiedXmlString = serializer.serializeToString(xmlDoc);

// In your Angular controller/service, trust the string
$scope.trustedContent = $sce.trustAsHtml(modifiedXmlString);

// Or use your existing filter (it will work with the properly formatted string now)
$scope.filteredContent = $filter('to_trusted')(modifiedXmlString);

Key Notes

  • Validation: Make sure your escaped string unescapes to valid XML—if not, DOMParser will return an error document. Double-check for unclosed tags or invalid characters.
  • Node.js Environment: If you’re working server-side, use libraries like xmldom or libxmljs instead of browser-native DOMParser—they provide similar parsing/serialization functionality.
  • Angular Filter Check: Your existing to_trusted filter is correctly set up, but handling the XML structure first ensures the trust attribute is properly embedded before trusting the content.

内容的提问来源于stack exchange,提问作者bellotas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:08:15