简体   繁体   English

在具有多个相似节点的C#中读取XML

[英]Reading XML in C# having multiple similar nodes

in a project I am reading XML file to get string data. 在一个项目中,我正在读取XML文件以获取字符串数据。 It works very well but with one exception. 它工作得很好,但有一个例外。 Here is the structure of XML File: 这是XML File的结构:

<Table>
    <row>
       <queryId>customAnalyticsParam</queryId>
       <queryStatement>
       1|-1|-1|-1
       </queryStatement>
    </row>
</Table>

The table tag contains multiple row tags. 表标签包含多个行标签。 Each row tag is distinguished by queryId tag. 每个行标记都由queryId标记区分。 Above structure works very well with following code: 上面的结构与以下代码配合得很好:

string query = "";
XmlDocument xd = new XmlDocument();
xd.Load(xml_query_filePath);
XmlNode xnode = xd.SelectNodes("/Table/row/queryId[.='" + id.Trim() + "']")[0];
query = xnode.NextSibling.NextSibling.InnerText;

In the above code in thrid line id is the queryId provided in the parameter of the function. 在上面的代码中,第三行ID是函数参数中提供的queryId。 The exception arises when XML is in following format: 当XML采用以下格式时,会出现异常:

<Table>
   <row>
      <queryId>
      customAnalyticsParam
      </queryId>
      <queryStatement>
      1|-1|-1|-1
      </queryStatement>
   </row>
</Table>

That is line spaces before and after in queryId node. 那就是queryId节点之前和之后的行间距。 Due to these line breaking spaces the code could not find the node and returns null. 由于这些换行符,代码无法找到该节点并返回null。

Please help me to find a way. 请帮助我找到一种方法。

Thanks 谢谢

尝试使用normalize-space

XmlNode xnode = xd.SelectNodes("/Table/row/queryId[normalize-space(.)='" + id.Trim() + "']").[0];

You can also use LINQ to XML with simple Trim() method to remove white-spaces 您还可以使用带有简单Trim()方法的LINQ to XML来删除空格

var xdoc = XDocument.Load(xml_query_filePath);
var statements = from r in xdoc.Descendants("row")
                 let queryId = (string)r.Element("queryId")
                 let statement = (string)r.Element("queryStatement")
                 where queryId.Trim() == id.Trim()
                 select statement.Trim();

Or if you need just first statement (note that as in your code, elements should exist in xml) 或者,如果您只需要第一个语句(请注意,如您的代码中所示,元素应存在于xml中)

var statement = xdoc.Descendants("row")
                    .First(r => r.Element("queryId").Value.Trim() == id.Trim())
                    .Element("queryStatement").Value.Trim();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM