Академический Документы
Профессиональный Документы
Культура Документы
XML-
XML
,
.
.NET
XML.
XML-,
, xml-
, c#.
, :
1
2
3
4
5
6
class User
{
public string Name { get; set; }
public int Age { get; set; }
public string Company { get; set; }
}
C# User:
1
2
3
User user1 = new User { Name = "Bill Gates", Age = 48, Company = "Microsoft" };
User user2 = new User { Name = "Larry Page", Age = 42, Company = "Google" };
List<User> users = new List<User> { user1, user2 };
xml
xml-:
1
2
3
4
5
6
7
8
9
10
11
<age>48</age>
</user>
</users>
- ?
- ,
. ,
:
1
2
3
4
5
6
7
8
9
10
11
12
13
XML,
C#.
XML
System.Xml
XML C# .
XML
System.Xml.
, xml-:
XmlNode:
xml.
XmlDocument: xml-
XmlElement: .
XmlNode
XmlAttribute:
XmlText: ,
,
XmlComment: xml
XmlNodeList:
,
xml, XmlNode,
:
Attributes
XmlAttributeCollection,
ChildNodes
HasChildNodes true,
FirstChild
LastChild
InnerText
InnerXml
xml
Name
, <user> -
Name "user"
ParentNode
. xml
users.xml
1
2
3
4
5
6
7
8
9
10
11
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using System.Xml;
class Program
{
static void Main(string[] args)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load("users.xml");
//
XmlElement xRoot = xDoc.DocumentElement;
//
foreach(XmlNode xnode in xRoot)
{
// name
if(xnode.Attributes.Count>0)
{
XmlNode attr = xnode.Attributes.GetNamedItem("name");
if (attr!=null)
Console.WriteLine(attr.Value);
}
// user
foreach(XmlNode childnode in xnode.ChildNodes)
{
// - company
if(childnode.Name=="company")
{
Console.WriteLine(": {0}", childnode.InnerText);
}
// age
if (childnode.Name == "age")
30
31
32
33
34
35
36
37
38
{
Console.WriteLine(": {0}", childnode.InnerText);
}
}
Console.WriteLine();
}
Console.Read();
}
}
xml,
XmlDocument xml-:xDoc.Load("users.xml");
xml
xDoc.DocumentElement.
.
foreach(XmlNode xnode in xRoot)
XML-
xml- (, ,
) XmlNode:
AppendChild:
InsertAfter:
InsertBefore:
RemoveAll:
RemoveChild:
XmlElement, XmlNode,
, :
CreateNode:
CreateElement: XmlDocument
CreateAttribute: XmlAttribute
CreateTextNode: XmlTextNode
CreateComment:
xml-
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
xDoc.Save("users.xml");
.
(xDoc.CreateElement("user")). ,
, .
( XmlText
companyText
xDoc.CreateTextNode("Facebook");).
user,
(xRoot.AppendChild(userElem);).
Save: xDoc.Save("users.xml")
xml- :
1
2
3
4
xml-:
1
2
3
4
5
6
7
XPath
XPath XML. ,
.
:
.
..
*
user
, "user"
@name
, @ (
"name")
@+
element[3]
,
//user
"user"
user[@name='Bill Gates']
.
"user" name='Bill Gates'
user[company='Microsoft']
.
"user", "company"
'Microsoft'
//user/company
"company",
"user"
XPath XmlElement:
SelectSingleNode(): .
,
SelectNodes(): XmlNodeList
xml- :
1
2
3
4
5
6
7
8
9
10
11
, user:
1
2
3
4
5
6
7
8
<user>:
name user:
1
2
3
:
Bill Gates
Larry Page
, name "Bill Gates":
1
2
3
, "company" "Microsoft":
1
2
3
, .
:
1
2
3