XML的结构分析+创建
2017-10-23 本文已影响0人
抬头自豪
XML是用于传输数据的一种结构。所以我把它看做是数据结构的方式。
构成方式为 :元素 + 元素值 + (元素的)属性 + 属性的值
例如:
<Alarm lock="true">
Ming
<Time>
StringValue
</Time>
</Alarm>
结构分析:
1. Alarm 为元素 : lock 为元素的属性,“True”为属性的值
2.Alarm元素的值 : Ming。
3.元素Time为Alarm元素的子元素
4.元素Time的值为StringVlue,但是却没有Time的属性
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//导入Xml命名空间
using System.Xml;
public class CreateXMLScripts : MonoBehaviour {
private void Start()
{
CreateXml();
}
void CreateXml()
{
/* 继承关系
-System.Object
-System.Xml.XmlNode(表示XML节点)
+System.Xml.XmlDocument (表示XML文档)
+System.Xml.XmlAttribute (表示XML属性)
-System.Xml.XmlLinkedNode
+System.Xml.XmlElement(表示XML元素)
*/
//创建Xml文件
XmlDocument Doc = new XmlDocument();
//1.为此Xml文件创建文件声明:申明版本,编码格式,
// standalone :The value must be either "yes" or "no". If this is null or String.Empty, the Save method does not write a standalone attribute on the XML declaration.
//独立的:这个值必须是“Yes”或“No”;Null 或者string.Empty都标示为"No",那么Save函数便不会在XMl的声明中写入独立的属性
// EnCoding :编码格式默认为:UTF-8 ;还有UTF-16
XmlDeclaration declaration = Doc.CreateXmlDeclaration("1.0", "utf-8",null);
//添加声明
Doc.AppendChild(declaration);
//2.创建第一个元素:即为根元素
XmlElement TransformNode = Doc.CreateElement("Transform");
//为元素创建属性
XmlAttribute attributeOfTransform = Doc.CreateAttribute("解释");
attributeOfTransform.Value = "游戏对象的变换";
//添加属性
TransformNode.Attributes.SetNamedItem(attributeOfTransform);
//把根元素添加到文件中
Doc.AppendChild(TransformNode);
//3.为TransformNode创建子元素
XmlElement PositionNode = Doc.CreateElement("Position");
//元素属性
XmlAttribute attributeOfPosition = Doc.CreateAttribute("解释");
attributeOfPosition.Value = "游戏对象的位置";
//添加属性 :
PositionNode.Attributes.SetNamedItem(attributeOfPosition);
//直接添加属性 PositionNode.SetAttribute("解释", "游戏对象的位置");
//把positionNode元素添加为Transform的子元素
TransformNode.AppendChild(PositionNode);
//4.为position创建子元素,包含的是坐标点
XmlNode xPosNode = Doc.CreateElement("X");
xPosNode.InnerText = "23";
PositionNode.AppendChild(xPosNode);
XmlNode yPosNode = Doc.CreateElement("Y");
yPosNode.InnerText = "3";
PositionNode.AppendChild(yPosNode);
XmlNode zPosNode = Doc.CreateElement("Z");
zPosNode.InnerText = "2";
PositionNode.AppendChild(zPosNode);
//5.保存
Doc.Save(Application.dataPath + "/Xml的创建" + "/myXml.xml");
}
}
当然这是效果:
image.png