首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

关于XML的操作,该怎么解决

2013-02-24 
关于XML的操作有这样的一个xmlabc i1 //bbc j2 /d k3 //b/a怎么实现简单方便

关于XML的操作
有这样的一个xml


<a>
<b>
<c i="1" />
</b>
<b>
<c j="2" />
<d k="3" />
</b>
</a>

怎么实现简单方便的实现
1.在第二个<b>结构下插入<e l="4" />
2.在第二个<b>结构后面再插入一个<b>结构

是用system.xml命名空间里面的类,还是用system.xml.linq里面的类方便呢?
[解决办法]
system.xml.linq里面的XElement就可以满足你的需求。
[解决办法]
XmlDocument,XmlElement,XmlNode足够处理你的问题了
[解决办法]
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"c:\test.xml");
XmlElement element = xmlDoc.CreateElement("e");
element.SetAttribute("i", "4");
xmlDoc.SelectSingleNode("/a/b[2]").AppendChild(element);
element = xmlDoc.CreateElement("b");
element.InnerText = string.Empty;
xmlDoc.DocumentElement.AppendChild(element);
xmlDoc.Save(@"c:\test.xml");

[解决办法]
static void Test1()
        {
            string str = "a2b1ci1b2cj2dk3";
            Match match = Regex.Match(str, @"^([a-z]\d)([a-z]\d
[解决办法]
[a-z]{2,2}\d)+$");
            if (match == null
                
[解决办法]
 !match.Success)
            {
                throw new InvalidOperationException("字符串无法转换成Xml");
            }
            XmlDocument doc = new XmlDocument();
            Group group = match.Groups[1];
            XmlElement root = CreateNode(group.Value, doc);
            doc.AppendChild(root);
            group = match.Groups[2];
            XmlElement element = null;
            foreach (Capture capture in group.Captures)
            {
                if (Regex.IsMatch(capture.Value,@"^[a-z]\d$"))
                {
                     element = CreateNode(capture.Value, doc);
                     root.AppendChild(element);


                }
                else if (Regex.IsMatch(capture.Value,@"^[a-z]{2,2}\d$")
                    && element != null)
                {
                    element.AppendChild(CreateNode(capture.Value,doc));
                }
            }
            Console.WriteLine(doc.InnerXml);
            Console.ReadLine();
            //output:<a><b><c i="1" /></b><b><c j="2" /><d k="3" /></b></a>
        }

        static XmlElement CreateNode(string str, XmlDocument doc)
        {
            if (string.IsNullOrEmpty(str))
            {
                throw new ArgumentNullException("str");
            }
            if (doc == null)
            {
                throw new ArgumentNullException("doc");
            }
            string nodeName = str.Substring(0, 1);
            XmlElement element = doc.CreateElement(nodeName);
            str = str.Substring(1);
            Match match = Regex.Match(str, @"^([a-z])(\d)$");
            if (match != null
                && match.Success)
            {
                string attributeName = match.Groups[1].Value;
                string value = match.Groups[2].Value;
                XmlAttribute attr = element.Attributes.Append(doc.CreateAttribute(attributeName));
                attr.Value = value;
            }
            return element;


        }

热点排行