C# XPathDocument parsing string to XML with BOM

南笙酒味 提交于 2019-12-12 03:28:46

问题


For a code in C#, I am parsing a string to XML using XPathDocument.

The string is retrieved from SDL Trados Studio and it depends on the XML that is being worked on (how it was originally created and loaded for translations) the string sometimes has a BOM sometimes not.

Edit: The 'xml' is actually parsed from the segments of the source and target text and the structure element. The textual elements are escaped for xml and the markup and text is joined in one string. So if the markup has BOM in the xliff, then the string will have BOM.

I am trying to actually parse any of the xmls, independent of encoding. So at this point my solution is to remove the BOM with Substring.

Here is my code:

//Recreate XML files (extractor returns two string arrays)
string strSourceXML = String.Join("", extractor.TextSrc);
string strTargetXML = String.Join("", extractor.TextTgt);

//strip BOM
strSourceXML = strSourceXML.Substring(strSourceXML.IndexOf("<?"));
strTargetXML = strTargetXML.Substring(strSourceXML.IndexOf("<?"));

//Transform XML with the preview XSL
var xSourceDoc = new XPathDocument(strSourceXML);
var xTargetDoc = new XPathDocument(strTargetXML);

I have searched for a better solution, through several articles, such as these, but I found no better solution yet:

  • XML - Data At Root Level is Invalid

  • Parsing XML with C#

  • Parsing complex XML with C#

  • Parsing : String to XML

  • XmlReader breaks on UTF-8 BOM

Any advice to solve this more elegantly?


回答1:


The constructor of XPathDocument taking a String argument https://msdn.microsoft.com/en-us/library/te0h7f95%28v=vs.110%29.aspx takes a URI with the XML file location. If you have a string with XML markup then use a StringReader over that string e.g.

XPathDocument xSourceDoc;
using (TextReader tr = new StringReader(strSourceXML))
{
  xSourceDoc = new XPathDocument(tr);
}


来源:https://stackoverflow.com/questions/37222980/c-sharp-xpathdocument-parsing-string-to-xml-with-bom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!