in a project I am reading XML file to get string data. It works very well but with one exception. Here is the structure of 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. 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. The exception arises when XML is in following format:
<Table>
<row>
<queryId>
customAnalyticsParam
</queryId>
<queryStatement>
1|-1|-1|-1
</queryStatement>
</row>
</Table>
That is line spaces before and after in queryId node. Due to these line breaking spaces the code could not find the node and returns 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
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)
var statement = xdoc.Descendants("row")
.First(r => r.Element("queryId").Value.Trim() == id.Trim())
.Element("queryStatement").Value.Trim();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.