有这样的一个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里面的类方便呢?
<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里面的类方便呢?
解决方案 »
- Sqlserver 索引的小问题
- System.Net.WebProxy是基于什么协议代理?
- pictureBox的问题?
- textbox 控键问题
- 如何读写.NET中的ini文档
- 运行时错误 (在本机上调试是好的,但是到了其它的电脑上调试的时候怎么会出现这样的问题呢?)
- 远程服务器返回错误: (500) 内部服务器错误
- 求微软MVP专家关于c#连接SQL SERVER2000 内存占用量不断上涨的问题。上升到一定程度后会自动关机
- C#.ini文件写不进去
- 如何把得到字符串“2003-08-17”代表的日期的是星期几?
- 菜鸟求解答,各种人士进
- 怎样跟踪winform应用程序发送到数据库的sql(oracle、mssql)
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");
a2b1ci1b2cj2dk3要转成xml
还有一些相同格式的字符串的也要转成相同格式的xml
比如
a3b1ci1b3cj2dk3el4b0
我不知道怎么做
转成
<a>
<b>
<c i="1" />
</b>
<b>
<c j="2" />
<d k="3" />
</b>
</a>
{
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;
}