|||
xml 样例:
<XML>
<Test>Hello World</Test>
<XML>
现在向XML里添加节点:
--------------------------
XmlDataDocument testXml = new XmlDataDocument();
testXml.LoadXml("<XML><Test>Hello World</Test></XML>");
XmlNode xn_root = testXml.DocumentElement;
for (int i = 0; i < 4; i++)
{
XmlElement xe_user = testXml.CreateElement("User");
XmlElement xe_name = testXml.CreateElement("Name");
xe_name.InnerText = "Fangjun Lee";
xe_user.AppendChild(xe_name);
XmlElement xe_sex = testXml.CreateElement("Sex");
xe_sex.InnerText = "Boy";
xe_user.AppendChild(xe_sex);
xn_root.AppendChild(xe_user);
}
---------------------------
结果:
-----
<XML>
<Test>Hello World</Test>
<User>
<Name>Fangjun Lee</Name>
<Sex>Boy</Sex>
</User>
<User>
<Name>Fangjun Lee</Name>
<Sex>Boy</Sex>
</User>
<User>
<Name>Fangjun Lee</Name>
<Sex>Boy</Sex>
</User>
<User>
<Name>Fangjun Lee</Name>
<Sex>Boy</Sex>
</User>
</XML>
---------------------------
现在想往每个User节点里添加一个Age元素
-----
(1)
-----
XmlNodeList xn_test = testXml.GetElementsByTagName("User");
XmlElement xe_age = testXml.CreateElement("Age");
xe_age.InnerText = "26";
for (int i = 0; i < xn_test.Count; i++)
{
xn_test[i+1].AppendChild(xe_age);
}
-----
结果:(没有达到预想结果)
-----
<XML>
<Test>Hello World</Test>
<User>
<Name>Fangjun Lee</Name>
<Sex>Boy</Sex>
</User>
<User>
<Name>Fangjun Lee</Name>
<Sex>Boy</Sex>
</User>
<User>
<Name>Fangjun Lee</Name>
<Sex>Boy</Sex>
</User>
<User>
<Name>Fangjun Lee</Name>
<Sex>Boy</Sex>
<Age>26<Age>
</User>
</XML>
-----
(2)
-----
XmlNodeList xn_test = testXml.GetElementsByTagName("User");
XmlElement xe_age = testXml.CreateElement("Age");
xe_age.InnerText = "26";
for (int i = 0; i < xn_test.Count; i++)
{
xn_test[i+1].AppendChild(xe_age.Clone());
}
-----
结果:
-----
<XML>
<Test>Hello World</Test>
<User>
<Name>Fangjun Lee</Name>
<Sex>Boy</Sex>
<Age>26<Age>
</User>
<User>
<Name>Fangjun Lee</Name>
<Sex>Boy</Sex>
<Age>26<Age>
</User>
<User>
<Name>Fangjun Lee</Name>
<Sex>Boy</Sex>
<Age>26<Age>
</User>
<User>
<Name>Fangjun Lee</Name>
<Sex>Boy</Sex>
<Age>26<Age>
</User>
</XML>
-----
(3)
-----
XmlNodeList xn_test = testXml.GetElementsByTagName("User");
for (int i = 0; i < xn_test.Count; i++)
{
XmlElement xe_age = testXml.CreateElement("Age");
xe_age.InnerText = "26";
xn_test[i+1].AppendChild(xe_age);
}
-----
结果:
-----
<XML>
<Test>Hello World</Test>
<User>
<Name>Fangjun Lee</Name>
<Sex>Boy</Sex>
<Age>26<Age>
</User>
<User>
<Name>Fangjun Lee</Name>
<Sex>Boy</Sex>
<Age>26<Age>
</User>
<User>
<Name>Fangjun Lee</Name>
<Sex>Boy</Sex>
<Age>26<Age>
</User>
<User>
<Name>Fangjun Lee</Name>
<Sex>Boy</Sex>
<Age>26<Age>
</User>
</XML>
-------------------------------------------------------
从这里可以看出,每次定义的 XmlNode 只能向XML Doc里添加一
次,如果要多次的话:(1)用Clone()方法或(2)每次重新定义
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-11-29 04:03
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社