我有一个类似于XML片段的字符串function listen_to_get_request(params, function callback(req) {
console.log(req.query);
}
,除了它包含反斜杠转义字符这一事实。我无法将此字符串加载到sMediaXML
中,使我能够检查并查看元素是否存在等...我需要保持字符串格式完全如下所示,因为其他代码将在以后依赖于它
XmlDocument
答案 0 :(得分:1)
你应该试试这个:
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.ConformanceLevel = ConformanceLevel.Document;
settings.CloseOutput = false;
MemoryStream strm = new MemoryStream();
using (XmlWriter writer = XmlWriter.Create(strm, settings))
{
writer.WriteStartElement("media");
writer.WriteStartElement("cd");
writer.WriteStartElement("burned");
writer.WriteAttributeString("value", "true");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteStartElement("vinyl");
writer.WriteStartElement("pressed");
writer.WriteAttributeString("value", "true");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndElement();
}
string sMediaXML = Encoding.UTF8.GetString((strm).ToArray());
Boolean bNodeExists;
string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (sMediaXML.StartsWith(_byteOrderMarkUtf8))
{
sMediaXML = sMediaXML.Remove(0, _byteOrderMarkUtf8.Length);
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(sMediaXML);
if (xmlDoc.SelectSingleNode("/media/cd/burned/@value").Value != null)
{
bNodeExists = true;
}
else
{
bNodeExists = false;
}
XDocument
,则应使用LoadXml
方法而不是Load
。直接从磁盘或流加载时使用Load
方法。XDocument
无法解析xml字符串,因为它包含指定顺序的UTF-8字节。更多信息here。还有另一种选择,要查看它,请查看此SO question。XPath
查询无论如何都无法使用,因为您没有定义任何“数字”元素。