Many times we need to use Xml files, but what is an Xml file?
Let’s use an example to illustrate: testResult.xml file
<?xml version="1.0" encoding="utf-8" ?> <Columns> <column id="序号"> <name>序号</name> </column> <column id="检验项目"> <name>检验项目</name> </column> <column id="单位"> <name>单位</name> </column> <column id="标准要求"> <name>标准要求</name> </column> <column id="检验结果"> <name>检验结果</name> </column> <column id="结论"> <name>结论</name> </column> </Columns>
The above is an Xml file. We know that Xml files are used to store data , so how do we traverse this data?
In fact, the simplest way is to use Linq:
private void GetTestResultXml() { List<string> iTestResultXml=new List<string>(); //定义并从xml文件中加载节点(根节点) XElement rootNode = XElement.Load(@"..\..\Xml\testResult.xml"); //查询语句: 获得根节点下name子节点(此时的子节点可以跨层次:孙节点、重孙节点......) IEnumerable<XElement> targetNodes = from target in rootNode.Descendants("column") select target; foreach (XElement node in targetNodes) { iTestResultXml.Add(node.Value); } }
In this way we can get all the data in the
In the testResult.xml file, we see that the
So what if we want to get his attributes instead of the content in his tags?
private void GetTestResultXml() { List<string> iXmlID = new List<string>(); //定义并从xml文件中加载节点(根节点) XElement rootNode = XElement.Load(@"..\..\Xml\testResult.xml"); //查询语句: 获得根节点下name子节点(此时的子节点可以跨层次:孙节点、重孙节点......) IEnumerable<XElement> targetNodes = from target in rootNode.Descendants("column") select target; foreach (XElement node in targetNodes) { iXmlID.Add(node.Attribute("id").Value); //获取指定属性的方法 } }
In this way we obtain the list iXmlID of the id attribute in the
The above is the detailed content of How does Linq in Xml traverse stored data?. For more information, please follow other related articles on the PHP Chinese website!