JavaScript中XML字符串转XML对象及添加trust属性问题
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,
DOMParserwill return an error document. Double-check for unclosed tags or invalid characters. - Node.js Environment: If you’re working server-side, use libraries like
xmldomorlibxmljsinstead of browser-nativeDOMParser—they provide similar parsing/serialization functionality. - Angular Filter Check: Your existing
to_trustedfilter is correctly set up, but handling the XML structure first ensures thetrustattribute is properly embedded before trusting the content.
内容的提问来源于stack exchange,提问作者bellotas

