source xml
文件为java object xml
input file
<?xml version="1.0" encoding="utf-16" standalone="yes"?>
<object class="MyMessage">
<object class="RequestMessage">
<field name="language">
<null/>
</field>
<field name="messageId">
<value class="java.lang.String">85036585</value>
</field>
</object>
</object>
我想使用c#将所有结构转换为普通的xml结构,还是有任何工具可以做?
预期的xml输出 -
<?xml version="1.0" encoding="utf-16" standalone="yes"?>
<MyMessage>
<RequestMessage>
<language>
</language>
<messageId>
85036585
</messageId>
</RequestMessage>
</MyMessage>
答案 0 :(得分:1)
我不确定下面的代码是否适用于所有情况,但它确实适用于您发布的xml。我正在使用xml linq的递归算法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
StreamReader reader = new StreamReader(FILENAME, Encoding.Unicode);
reader.ReadLine(); //skip xml identification due to unicode not being recognized.
XDocument doc = XDocument.Load(reader);
XElement root = doc.Root;
string xmlHeader = string.Format("<?xml version=\"1.0\" encoding=\"utf-16\" standalone=\"yes\"?><{0}></{0}>", (string)root.Attributes().FirstOrDefault());
XDocument newDoc = XDocument.Parse(xmlHeader);
XElement newRoot = newDoc.Root;
RecursiveParse(root, newRoot);
}
static void RecursiveParse(XElement parent, XElement newParent)
{
List<XElement> children = parent.Elements().ToList();
if (children != null)
{
foreach (XElement child in children)
{
if (child.Name.LocalName != "null")
{
string innerTag = (string)(XElement)child.FirstNode;
XElement newChild = new XElement((string)child.Attributes().FirstOrDefault());
newParent.Add(newChild);
if (innerTag != "")
{
newParent.Add(innerTag);
}
else
{
RecursiveParse(child, newChild);
}
}
}
}
}
}
}