<Row>
<Cell ss:StyleID="s16"><Data ss:Type="String">Name</Data></Cell>
<Cell ss:StyleID="s16"><Data ss:Type="String">value1</Data></Cell>
<Cell ss:StyleID="s16"><Data ss:Type="String">value2</Data></Cell>
<Cell ss:StyleID="s17"><Data ss:Type="String">value3</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s18"><Data ss:Type="String">B</Data></Cell>
<Cell ss:StyleID="s18"><Data ss:Type="Number">31</Data></Cell>
<Cell ss:StyleID="s18"><Data ss:Type="Number">47</Data></Cell>
<Cell ss:StyleID="s19"><Data ss:Type="Number">148</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s18"><Data ss:Type="String">C</Data></Cell>
<Cell ss:StyleID="s18"><Data ss:Type="Number">40</Data></Cell>
<Cell ss:StyleID="s18"><Data ss:Type="Number">78</Data></Cell>
<Cell ss:StyleID="s19"><Data ss:Type="Number">312</Data></Cell>
</Row>
<Row>
这是我的xlm。我想在value3列中搜索双阈值,如果threshold的值是200,我想在单独的变量中返回value3列(C,40,78,312)中直接较大值的行。我也有一些警告,解引用可能为空的引用,将空文字或可能的空值转换为非空类型。如何解决这个问题。这是使用的代码。任何帮助吗?
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(Properties.Resources.Data);double threshold=200;
XmlNodeList rows = xmlDoc.SelectNodes("//Row[Cell[4][number(Data) > " + threshold + "]]");
foreach (XmlNode row in rows)
{
XmlNodeList cells = row.SelectNodes("Cell/Data");
string cell1 = cells[0].InnerText;
double cell2 = double.Parse(cells[1].InnerText);
double cell3 = double.Parse(cells[2].InnerText);
}
使用Xml Linq。我将xml读入一个数据表,然后搜索表
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
namespace ConsoleApplication2
{
class Program
{
const string FILENAME = @"c:temptest.xml";
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("A", typeof(string));
dt.Columns.Add("B", typeof(int));
dt.Columns.Add("C", typeof(int));
dt.Columns.Add("D", typeof(int));
object[] row = new object[4];
XDocument doc = XDocument.Load(FILENAME);
foreach (XElement xRow in doc.Descendants("Row"))
{
int index = 0;
foreach (XElement cell in xRow.Descendants("Data"))
{
if(index == 0)
{
row[index] = (string)cell;
}
else
{
row[index] = (int)cell;
}
index++;
}
dt.Rows.Add(row);
}
dt = dt.AsEnumerable().OrderBy(x => x.Field<int>("D")).CopyToDataTable();
int threshhold = 200;
DataRow results = dt.AsEnumerable().Where(x => x.Field<int>("D") > threshhold).First();
}
}
}
您可以使用Newtonsoft。Json
using Newtonsoft.Json;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
var rowJson = JsonConvert.SerializeXmlNode(xmlDoc, Newtonsoft.Json.Formatting.Indented, true);
var jObj = JObject.Parse(rowJson);
List<string> values = jObj["Row"]
.Select(x => x["Cell"])
.Where(x => x.Any(x => (string)x["Data"]["@Type"] == "Number" && (int)x["Data"]["#text"] > 200))
.FirstOrDefault()
//.Where(x => (string)x["Data"]["@Type"] == "Number")
.Select(x => x["Data"]["#text"].ToString())
.ToList();
结果
["C","40","78","312"]
如果你想单独到达值,你可以使用下面的代码
var val0 = values[0]; // "C"
var val1 = values[1]; // "40"
// and so on