zoukankan
html css js c++ java
LINQ to XML一些基本查询
Code
/**/
///
/根据元素的名称进行筛选(有命名空间)
//
XNamespace aw = "
http://www.adventure-works.com
";
//
XElement po = XElement.Load("PurchaseOrderInNamespace.xml");
//
IEnumerable<XElement> items =
//
from el in po.Descendants(aw + "ProductName")
//
select el;
//
foreach (XElement prdName in items)
//
Console.WriteLine(prdName.Name + ":" + (string)prdName);
/**/
///
/链接轴方法
//
XElement purchaseOrders = XElement.Load("PurchaseOrders.xml");
//
IEnumerable<XElement> names =
//
from el in purchaseOrders
//
.Elements("PurchaseOrder")
//
.Elements("Address")
//
.Elements("Name")
//
select el;
//
foreach (XElement e in names)
//
Console.WriteLine(e);
/**/
///
/链接轴方法,有时,当可能存在或不存在间隔上级时,您希望在特定的元素深度,检索所有的元素
//
XElement root = XElement.Load("Irregular.xml");
//
IEnumerable<XElement> configParameters =
//
root.Elements("Customer").Elements("Config").
//
Elements("ConfigParameter");
//
foreach (XElement cp in configParameters)
//
Console.WriteLine(cp);
/**/
///
/检索单个子元素
//
XElement po = XElement.Load("PurchaseOrder.xml");
//
XElement e = po.Element("DeliveryNotes");
//
Console.WriteLine(e);
/**/
///
/检索索性的集合
//
XElement val = new XElement("Value",
//
new XAttribute("ID", "1243"),
//
new XAttribute("Type", "int"),
//
new XAttribute("ConvertableTo", "double"),
//
"100");
//
IEnumerable<XAttribute> listOfAttributes =
//
from att in val.Attributes()
//
select att;
//
foreach (XAttribute a in listOfAttributes)
//
Console.WriteLine(a);
/**/
///
/检索单个属性
//
XElement cust = new XElement("PhoneNumbers",
//
new XElement("Phone",
//
new XAttribute("type", "home"),
//
"555-555-5555"),
//
new XElement("Phone",
//
new XAttribute("type", "work"),
//
"555-555-6666")
//
);
//
IEnumerable<XElement> elList =
//
from el in cust.Descendants("Phone")
//
select el;
//
foreach (XElement el in elList)
//
Console.WriteLine((string)el.Attribute("type"));
/**/
///
/检索属性值
//
XElement root = new XElement("Root",
//
new XAttribute("Attr", "abcde")
//
);
//
Console.WriteLine(root);
//
string str = (string)root.Attribute("Attr");
//
Console.WriteLine(str);
#endregion
基本查询
#region
基本查询
/**/
///
/查找具有特定属性的元素
//
XElement root = XElement.Load("PurchaseOrder.xml");
//
IEnumerable<XElement> address =
//
from el in root.Elements("Address")
//
where (string)el.Attribute("Type") == "Billing"
//
select el;
//
foreach (XElement el in address)
//
Console.WriteLine(el);
/**/
///
/查找具有特定子元素的元素
//
XElement root = XElement.Load("TestConfig.xml");
//
IEnumerable<XElement> tests =
//
from el in root.Elements("Test")
//
where (string)el.Element("CommandLine") == "Examp2.EXE"
//
select el;
//
foreach (XElement el in tests)
//
Console.WriteLine((string)el.Attribute("TestId"));
//
查询 XDocument 与查询 XElement
//
//
Create a simple document and write it to a file
//
File.WriteAllText("Test.xml", @"<Root>
//
<Child1>1</Child1>
//
<Child2>2</Child2>
//
<Child3>3</Child3>
//
</Root>");
//
Console.WriteLine("Querying tree loaded with XElement.Load");
//
Console.WriteLine("----");
//
XElement doc = XElement.Load("Test.xml");
//
IEnumerable<XElement> childList =
//
from el in doc.Elements()
//
select el;
//
foreach (XElement e in childList)
//
Console.WriteLine(e);
//
Console.WriteLine("Querying tree loaded with XDocument.Load");
//
Console.WriteLine("----");
//
XDocument doc = XDocument.Load("Test.xml");
//
IEnumerable<XElement> childList =
//
from el in doc.Elements()
//
select el;
//
foreach (XElement e in childList)
//
Console.WriteLine(e);
//
//
查找具有特定元素名称的子代
//
XElement root = XElement.Parse(@"<root>
//
<para>
//
<r>
//
<t>Some text </t>
//
</r>
//
<n>
//
<r>
//
<t>that is broken up into </t>
//
</r>
//
</n>
//
<n>
//
<r>
//
<t>multiple segments.</t>
//
</r>
//
</n>
//
</para>
//
</root>");
//
IEnumerable<string> textSegs =
//
from seg in root.Descendants("t")
//
select (string)seg;
//
string str = textSegs.Aggregate(new StringBuilder(),
//
(sb, i) => sb.Append(i),
//
sp => sp.ToString()
//
);
//
Console.WriteLine(str);
//
//
使用 Descendants 方法查找单个后代
//
XElement root = XElement.Parse(@"<Root>
//
<Child1>
//
<GrandChild1>GC1 Value</GrandChild1>
//
</Child1>
//
<Child2>
//
<GrandChild2>GC2 Value</GrandChild2>
//
</Child2>
//
<Child3>
//
<GrandChild3>GC3 Value</GrandChild3>
//
</Child3>
//
<Child4>
//
<GrandChild4>GC4 Value</GrandChild4>
//
</Child4>
//
</Root>");
//
string grandChild3 = (string)
//
(from el in root.Descendants("GrandChild3")
//
select el).First();
//
Console.WriteLine(grandChild3);
/**/
///
/编写使用复杂筛选的查询
//
XElement root = XElement.Load("PurchaseOrders.xml");
//
IEnumerable<XElement> purchaseOrders =
//
from el in root.Elements("PurchaseOrder")
//
where
//
(from add in el.Elements("Address")
//
where
//
(string)add.Attribute("Type") == "Shipping" &&
//
(string)add.Element("State") == "NY"
//
select add)
//
.Any()
//
select el;
//
foreach (XElement el in purchaseOrders)
//
Console.WriteLine((string)el.Attribute("PurchaseOrderNumber"));
//
//
筛选可选元素
//
XElement root = XElement.Parse(@"<Root>
//
<Child1>
//
<Text>Child One Text</Text>
//
<Type Value=""Yes""/>
//
</Child1>
//
<Child2>
//
<Text>Child Two Text</Text>
//
<Type Value=""Yes""/>
//
</Child2>
//
<Child3>
//
<Text>Child Three Text</Text>
//
<Type Value=""No""/>
//
</Child3>
//
<Child4>
//
<Text>Child Four Text</Text>
//
<Type Value=""Yes""/>
//
</Child4>
//
<Child5>
//
<Text>Child Five Text</Text>
//
</Child5>
//
</Root>");
//
var cList =
//
from typeElement in root.Elements().Elements("Type")
//
where (string)typeElement.Attribute("Value") == "Yes"
//
select (string)typeElement.Parent.Element("Text");
//
foreach (string str in cList)
//
Console.WriteLine(str);
/**/
///
/对元素进行排序
//
XElement root = XElement.Load("Data.xml");
//
IEnumerable<decimal> prices =
//
from el in root.Elements("Data")
//
let price = (decimal)el.Element("Price")
//
orderby price
//
select price;
//
foreach (decimal el in prices)
//
Console.WriteLine(el);
/**/
///
/对多个键上的元素进行排序
//
XElement co = XElement.Load("CustomersOrders.xml");
//
var sortedElements =
//
from c in co.Element("Orders").Elements("Order")
//
orderby (string)c.Element("ShipInfo").Element("ShipPostalCode"),
//
(DateTime)c.Element("OrderDate")
//
select new
//
{
//
CustomerID = (string)c.Element("CustomerID"),
//
EmployeeID = (string)c.Element("EmployeeID"),
//
ShipPostalCode = (string)c.Element("ShipInfo").Element("ShipPostalCode"),
//
OrderDate = (DateTime)c.Element("OrderDate")
//
};
//
foreach (var r in sortedElements)
//
Console.WriteLine("CustomerID:{0} EmployeeID:{1} ShipPostalCode:{2} OrderDate:{3:d}",
//
r.CustomerID, r.EmployeeID, r.ShipPostalCode, r.OrderDate);
//
计算中间值
//
XElement root = XElement.Load("Data.xml");
//
IEnumerable<decimal> extensions =
//
from el in root.Elements("Data")
//
let extension = (decimal)el.Element("Quantity") * (decimal)el.Element("Price")
//
where extension >= 25
//
orderby extension
//
select extension;
//
foreach (decimal ex in extensions)
//
Console.WriteLine(ex);
//
//
编写基于上下文查找元素的查询
//
XElement doc = XElement.Parse(@"<Root>
//
<p id=""1""/>
//
<ul>abc</ul>
//
<Child>
//
<p id=""2""/>
//
<notul/>
//
<p id=""3""/>
//
<ul>def</ul>
//
<p id=""4""/>
//
</Child>
//
<Child>
//
<p id=""5""/>
//
<notul/>
//
<p id=""6""/>
//
<ul>abc</ul>
//
<p id=""7""/>
//
</Child>
//
</Root>");
//
IEnumerable<XElement> items =
//
from e in doc.Descendants("p")
//
let z = e.ElementsAfterSelf().FirstOrDefault()
//
where z != null && z.Name.LocalName == "ul"
//
select e;
//
foreach (XElement e in items)
//
Console.WriteLine("id = {0}", (string)e.Attribute("id"));
//
调试空查询结果集
//
XElement root = XElement.Parse(
//
@"<Root xmlns='
http://www.adventure-works.com
'>
//
<Child>1</Child>
//
<Child>2</Child>
//
<Child>3</Child>
//
<AnotherChild>4</AnotherChild>
//
<AnotherChild>5</AnotherChild>
//
<AnotherChild>6</AnotherChild>
//
</Root>");
//
IEnumerable<XElement> c1 =
//
from el in root.Elements("Child")
//
select el;
//
Console.WriteLine("Result set follows:");
//
foreach (XElement el in c1)
//
Console.WriteLine((int)el);
//
Console.WriteLine("End of result set");
//
XElement root = XElement.Parse(
//
@"<Root xmlns='
http://www.adventure-works.com
'>
//
<Child>1</Child>
//
<Child>2</Child>
//
<Child>3</Child>
//
<AnotherChild>4</AnotherChild>
//
<AnotherChild>5</AnotherChild>
//
<AnotherChild>6</AnotherChild>
//
</Root>");
//
XNamespace aw = "
http://www.adventure-works.com
";
//
IEnumerable<XElement> c1 =
//
from el in root.Elements(aw + "Child")
//
select el;
//
Console.WriteLine("Result set follows:");
//
foreach (XElement el in c1)
//
Console.WriteLine((int)el);
//
Console.WriteLine("End of result set");
#endregion
投影和转换
#region
投影和转换
//
通过 LINQ to XML 使用字典
//
Dictionary<string, string> dict = new Dictionary<string, string>();
//
dict.Add("Child1", "Value1");
//
dict.Add("Child2", "Value2");
//
dict.Add("Child3", "Value3");
//
dict.Add("Child4", "Value4");
//
XElement root = new XElement("Root",
//
from keyValue in dict
//
select new XElement(keyValue.Key, keyValue.Value)
//
);
//
Console.WriteLine(root);
//
XElement root = new XElement("Root",
//
new XElement("Child1", "Value1"),
//
new XElement("Child2", "Value2"),
//
new XElement("Child3", "Value3"),
//
new XElement("Child4", "Value4")
//
);
//
Dictionary<string, string> dict = new Dictionary<string, string>();
//
foreach (XElement el in root.Elements())
//
dict.Add(el.Name.LocalName, el.Value);
//
foreach (string str in dict.Keys)
//
Console.WriteLine("{0}:{1}", str, dict[str]);
/**/
///
/转换 XML 树的形状
//
XElement co = XElement.Load("CustomersOrders.xml");
//
XElement newCustOrd =
//
new XElement("Root",
//
from cust in co.Element("Customers").Elements("Customer")
//
select new XElement("Customer",
//
cust.Attributes(),
//
cust.Elements(),
//
new XElement("Orders",
//
from ord in co.Element("Orders").Elements("Order")
//
where (string)ord.Element("CustomerID") == (string)cust.Attribute("CustomerID")
//
select new XElement("Order",
//
ord.Attributes(),
//
ord.Element("EmployeeID"),
//
ord.Element("OrderDate"),
//
ord.Element("RequiredDate"),
//
ord.Element("ShipInfo")
//
)
//
)
//
)
//
);
//
Console.WriteLine(newCustOrd);
/**/
///
/投影匿名类型
//
XElement custOrd = XElement.Load("CustomersOrders.xml");
//
var custList =
//
from el in custOrd.Element("Customers").Elements("Customer")
//
select new
//
{
//
CustomerID = (string)el.Attribute("CustomerID"),
//
CompanyName = (string)el.Element("CompanyName"),
//
ContactName = (string)el.Element("ContactName")
//
};
//
foreach (var cust in custList)
//
Console.WriteLine("{0}:{1}:{2}", cust.CustomerID, cust.CompanyName, cust.ContactName);
/**/
///
/从 XML 生成文本文件
//
XElement custOrd = XElement.Load("CustomersOrders.xml");
//
string csv =
//
(from el in custOrd.Element("Customers").Elements("Customer")
//
select
//
String.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}{10}",
//
(string)el.Attribute("CustomerID"),
//
(string)el.Element("CompanyName"),
//
(string)el.Element("ContactName"),
//
(string)el.Element("ContactTitle"),
//
(string)el.Element("Phone"),
//
(string)el.Element("FullAddress").Element("Address"),
//
(string)el.Element("FullAddress").Element("City"),
//
(string)el.Element("FullAddress").Element("Region"),
//
(string)el.Element("FullAddress").Element("PostalCode"),
//
(string)el.Element("FullAddress").Element("Country"),
//
Environment.NewLine
//
)
//
)
//
.Aggregate(
//
new StringBuilder(),
//
(sb, s) => sb.Append(s),
//
sb => sb.ToString()
//
);
//
Console.WriteLine(csv);
//
//
从 CSV 文件生成 XML
//
//
Create the text file.
//
string csvString = @"GREAL,Great Lakes Food Market,Howard Snyder,Marketing Manager,(503) 555-7555,2732 Baker Blvd.,Eugene,OR,97403,USA
//
HUNGC,Hungry Coyote Import Store,Yoshi Latimer,Sales Representative,(503) 555-6874,City Center Plaza 516 Main St.,Elgin,OR,97827,USA
//
LAZYK,Lazy K Kountry Store,John Steel,Marketing Manager,(509) 555-7969,12 Orchestra Terrace,Walla Walla,WA,99362,USA
//
LETSS,Let's Stop N Shop,Jaime Yorres,Owner,(415) 555-5938,87 Polk St. Suite 5,San Francisco,CA,94117,USA";
//
File.WriteAllText("cust.csv", csvString);
//
//
Read into an array of strings.
//
string[] source = File.ReadAllLines("cust.csv");
//
XElement cust = new XElement("Root",
//
from str in source
//
let fields = str.Split(',')
//
select new XElement("Customer",
//
new XAttribute("CustomerID", fields[0]),
//
new XElement("CompanyName", fields[1]),
//
new XElement("ContactName", fields[2]),
//
new XElement("ContactTitle", fields[3]),
//
new XElement("Phone", fields[4]),
//
new XElement("FullAddress",
//
new XElement("Address", fields[5]),
//
new XElement("City", fields[6]),
//
new XElement("Region", fields[7]),
//
new XElement("PostalCode", fields[8]),
//
new XElement("Country", fields[9])
//
)
//
)
//
);
//
Console.WriteLine(cust);
#endregion
高级查询技术
#region
高级查询技术
/**/
///
/联接两个集合
//
XmlSchemaSet schemas = new XmlSchemaSet();
//
schemas.Add("", "CustomersOrders.xsd");
//
Console.Write("Attempting to validate, ");
//
XDocument custOrdDoc = XDocument.Load("CustomersOrders.xml");
//
bool errors = false;
//
custOrdDoc.Validate(schemas, (o, e) =>
//
{
//
Console.WriteLine("{0}", e.Message);
//
errors = true;
//
});
//
Console.WriteLine("custOrdDoc {0}", errors ? "did not validate" : "validated");
//
if (!errors)
//
{
//
//
Join customers and orders, and create a new XML document with
//
//
a different shape.
//
//
The new document contains orders only for customers with a
//
//
CustomerID > 'K'
//
XElement custOrd = custOrdDoc.Element("Root");
//
XElement newCustOrd = new XElement("Root",
//
from c in custOrd.Element("Customers").Elements("Customer")
//
join o in custOrd.Element("Orders").Elements("Order")
//
on (string)c.Attribute("CustomerID") equals
//
(string)o.Element("CustomerID")
//
where ((string)c.Attribute("CustomerID")).CompareTo("K") > 0
//
select new XElement("Order",
//
new XElement("CustomerID", (string)c.Attribute("CustomerID")),
//
new XElement("CompanyName", (string)c.Element("CompanyName")),
//
new XElement("ContactName", (string)c.Element("ContactName")),
//
new XElement("EmployeeID", (string)o.Element("EmployeeID")),
//
new XElement("OrderDate", (DateTime)o.Element("OrderDate"))
//
)
//
);
//
Console.WriteLine(newCustOrd);
//
}
/**/
///
/使用分组创建层次结构
//
XElement doc = XElement.Load("Data.xml");
//
var newData =
//
new XElement("Root",
//
from data in doc.Elements("Data")
//
group data by (string)data.Element("Category") into groupedData
//
select new XElement("Group",
//
new XAttribute("ID", groupedData.Key),
//
from g in groupedData
//
select new XElement("Data",
//
g.Element("Quantity"),
//
g.Element("Price")
//
)
//
)
//
);
//
Console.WriteLine(newData);
/**/
///
/执行文本到 XML 的流式转换
//
StreamReader sr = new StreamReader("People.txt");
//
XStreamingElement xmlTree = new XStreamingElement("Root",
//
from line in sr.Lines()
//
let items = line.Split(',')
//
where !line.StartsWith("#")
//
select new XElement("Person",
//
new XAttribute("ID", items[0]),
//
new XElement("First", items[1]),
//
new XElement("Last", items[2]),
//
new XElement("Occupation", items[3])
//
)
//
);
//
Console.WriteLine(xmlTree);
//
sr.Close();
/**/
///
/使用 XPath 查询 LINQ to XML
//
XElement root = new XElement("Root",
//
new XElement("Child1", 1),
//
new XElement("Child1", 2),
//
new XElement("Child1", 3),
//
new XElement("Child2", 4),
//
new XElement("Child2", 5),
//
new XElement("Child2", 6)
//
);
//
IEnumerable<XElement> list = root.XPathSelectElements("./Child2");
//
foreach (XElement el in list)
//
Console.WriteLine(el);
#endregion
修改XML树
#region
修改XML树
/**/
///
/将属性转换为元素
//
XElement root = XElement.Load("Data1.xml");
//
foreach (XAttribute att in root.Attributes())
//
{
//
root.Add(new XElement(att.Name, (string)att));
//
}
//
root.Attributes().Remove();
//
Console.WriteLine(root);
/**/
///
/函数构造
//
XElement root = XElement.Load("Data1.xml");
//
XElement newTree = new XElement("Root",
//
root.Element("Child1"),
//
from att in root.Attributes()
//
select new XElement(att.Name, (string)att)
//
);
//
Console.WriteLine(newTree);
/**/
///
/向树中添加元素
//
XElement srcTree = new XElement("Root",
//
new XElement("Element1", 1),
//
new XElement("Element2", 2),
//
new XElement("Element3", 3),
//
new XElement("Element4", 4),
//
new XElement("Element5", 5)
//
);
//
XElement xmlTree = new XElement("Root",
//
new XElement("Child1", 1),
//
new XElement("Child2", 2),
//
new XElement("Child3", 3),
//
new XElement("Child4", 4),
//
new XElement("Child5", 5)
//
);
//
xmlTree.Add(new XElement("NewChild", "new content"));
//
xmlTree.Add(
//
from el in srcTree.Elements()
//
where (int)el > 3
//
select el
//
);
/**/
///
/ Even though Child9 does not exist in srcTree, the following statement will not
///
/ throw an exception, and nothing will be added to xmlTree.
//
xmlTree.Add(srcTree.Element("Child9"));
//
Console.WriteLine(xmlTree);
//
移除元素
//
XElement root = XElement.Parse(@"<Root>
//
<Child1>
//
<GrandChild1/>
//
<GrandChild2/>
//
<GrandChild3/>
//
</Child1>
//
<Child2>
//
<GrandChild4/>
//
<GrandChild5/>
//
<GrandChild6/>
//
</Child2>
//
<Child3>
//
<GrandChild7/>
//
<GrandChild8/>
//
<GrandChild9/>
//
</Child3>
//
</Root>");
//
root.Element("Child1").Element("GrandChild1").Remove();
//
root.Element("Child2").Elements().ToList().Remove();
//
root.Element("Child3").Elements().Remove();
//
Console.WriteLine(root);
/**/
///
/维护名称/值对
///
/ Create an element with no content.
//
XElement root = new XElement("Root");
/**/
///
/ Add a number of name/value pairs as attributes.
//
root.SetAttributeValue("Top", 22);
//
root.SetAttributeValue("Left", 20);
//
root.SetAttributeValue("Bottom", 122);
//
root.SetAttributeValue("Right", 300);
//
root.SetAttributeValue("DefaultColor", "Color.Red");
//
Console.WriteLine(root);
/**/
///
/ Replace the value of Top.
//
root.SetAttributeValue("Top", 10);
//
Console.WriteLine(root);
/**/
///
/ Remove DefaultColor.
//
root.SetAttributeValue("DefaultColor", null);
//
Console.WriteLine(root);
/**/
///
/元素名称/值对
///
/ Create an element with no content.
//
XElement root = new XElement("Root");
/**/
///
/ Add a number of name/value pairs as elements.
//
root.SetElementValue("Top", 22);
//
root.SetElementValue("Left", 20);
//
root.SetElementValue("Bottom", 122);
//
root.SetElementValue("Right", 300);
//
root.SetElementValue("DefaultColor", "Color.Red");
//
Console.WriteLine(root);
//
Console.WriteLine("----");
/**/
///
/ Replace the value of Top.
//
root.SetElementValue("Top", 10);
//
Console.WriteLine(root);
//
Console.WriteLine("----");
/**/
///
/ Remove DefaultColor.
//
root.SetElementValue("DefaultColor", null);
//
Console.WriteLine(root);
#endregion
查看全文
相关阅读:
php jquery+ajax写批量删除
thinkphp 验证码
thinkphp 框架中的一部分方法解析
ThinkPHP框架的增删改
ThinkPHP 框架模型
ThinkPHP框架之空控制器
江苏省盐城市响水县运河镇开源路商业街商铺及套间招商招租出售
苏州鼎耀文化传媒有限公司
怎么给罗技K480 增加Home、End键
C#实现APK自动打包
原文地址:https://www.cnblogs.com/zwl12549/p/1324571.html
最新文章
C语言学习笔记之字符串拼接的2种方法——strcat、sprintf
iOS(Swift)学习笔记之SwiftyJSON的使用
iOS(Swift)学习笔记之去除UINavigationBar下方横线
iOS(Swift)学习笔记之SnapKit+自定义UI组件
RxSwift学习笔记之Subject
博客改版通知
Hadoop源码学习笔记(6)——从ls命令一路解剖
Hadoop源码学习笔记(5) ——回顾DataNode和NameNode的类结构
Hadoop源码学习笔记(4) ——Socket到RPC调用
Hadoop源码学习笔记(3) ——初览DataNode及学习线程
热门文章
Hadoop源码学习笔记(2) ——进入main函数打印包信息
Hadoop源码学习笔记(1) ——第二季开始——找到Main函数及读一读Configure类
我对编程的一些感悟
Hadoop学习笔记(10) ——搭建源码学习环境
Hadoop学习笔记(9) ——源码初窥
Hadoop学习笔记(8) ——实战 做个倒排索引
c#中关于compare比较的一点注意事项
年月日的三级联动
用javascript简单写的判断电话号码
php修改密码
Copyright © 2011-2022 走看看