XDocument,它说节点是文本,但它是一个元素
本文关键字:元素 一个 文本 节点 XDocument | 更新日期: 2023-09-27 17:57:49
我正在阅读一个XML,它包含这样的标签:
<source><bpt id="1"><donottranslate></bpt><ph id="2">($ T_353_1 Parent ID $)</ph><ept id="1"></donottranslate></ept></source>
当阅读source
节点时,我发现这个节点类型是Text,但它应该是Element。这是我正在接收的XML,我无法更改它。
你知道我该怎么解决这个问题吗?
这是我的代码:
XDocument doc = XDocument.Load(fileName, LoadOptions.PreserveWhitespace);
foreach (var elUnit in doc.Descendants("trans-unit"))
{
if (elUnit.AttributeString("translate").ToString() == "no")
{
foreach (var elSource in elUnit.Elements("source"))
{
string text = "";
foreach (var node in elSource.DescendantNodes().Where(n => XmlNodeType.Text == n.NodeType).ToList())
{
//When reading that "source" node, it enters inside this code
感谢
首先检查您的XML是否是格式良好的
- http://www.w3schools.com/xml/xml_validator.asp
- http://chris.photobooks.com/xml/default.htm
我可以用
//using System.Xml.Linq;
var str = "<source><bpt id='"1'"><donottranslate></bpt>" +
"<ph id='"2'">($ T_353_1 Parent ID $)</ph>" +
"<ept id='"1'"></donottranslate></ept></source>";
XElement element = XElement.Parse(str);
Console.WriteLine(element);
输出是这个
<source>
<bpt id="1"><donottranslate></bpt>
<ph id="2">($ T_353_1 Parent ID $)</ph>
<ept id="1"></donottranslate></ept>
</source>
如果这个例子不够充分,请提供一些代码示例以获得更多帮助。
最后,我解决了这个检查节点是否正确的问题:
if (System.Security.SecurityElement.IsValidText(text.XmlDecodeEntities()))