在C#中将文本转换为xml [英] Convert text to xml in C#

查看:109
本文介绍了在C#中将文本转换为xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿家伙使用下面的代码我试图将我的文本文件转换为xml但我还没有成功。经过多次尝试和努力,我想把它发布在代码项目上。如果可能请检查我的代码并为我提供相关的解决方案。



  string  statusFilePath = Directory.GetCurrentDirectory()。ToString()+   \\Status \\ ; 
foreach 字符串文件 in Directory.GetFiles(statusFilePath, wpasset * .txt))
{
string filename = Path.GetFileNameWithoutExtension(file);
string content = File.ReadAllText(file);
string statusfilename = Directory.GetCurrentDirectory()。ToString()+ \\\\Status \\\\ + 的test.xml;

// string statusFilePath1 = Directory.GetCurrentDirectory()。ToString()+\ \\\Status \\\\+* .xml;
正则表达式= 正则表达式( @ ##(?< parent> \w +)\ r \ n(?< children> ; [\ w] +)\\\\ n((?< values> [\ S] +)(\\\\ n(?!#)| $))+ ,RegexOptions.None);
XElement xeRoot = new XElement( wpassetd ); // root node
foreach (匹配m in expression.Matches(content))
{
XElement xeParent = new XElement(m.Groups [ parent]。Value);

string [] children = m.Groups [ children]。Value.Split(' '); // 将空格用作子项的分隔符

foreach (捕获上限 m.Groups [ values]。捕获)
{
XElement xeChild = new XElement( data); // 将名称child更改为任何合适的
string [] values = cap.Value.Split( new string [] { },StringSplitOptions.None);
// 检查子项和值计数是否相等
if (children.Length!= values.Length)
throw new 异常( 子项数和值不匹配。);

for int i = 0 ; i < children.Length; i ++)
{
XElement xeChildValue = new XElement(children [i] .ToLower());

// xeChildValue.Value = values [i];

// xeChildValue.Value = String.Format(![CDATA [{0}]] ,values [i]);
XCData cdata = new XCData(values [i]);
xeChildValue.Add(cdata);

xeChild.Add(xeChildValue);

}
xeParent.Add(xeChild);

}

xeRoot.Add(xeParent);
}
XDocument xmldoc = new XDocument();
string 结果;
xmldoc.Add(xeRoot);
xmldoc.Save(statusfilename);
result = Path.GetFileName(statusfilename);
// xmldoc.Save(@test.xml);





和我的文本文件是:

 2015 -04-07 14:49:33:(INFO):类别:HandleOutPut:开始登录2015-04-07 14:49:33 
2015-04-07 14:49:33 :(警告):类别:IsRunAsAdmin:运行此进程的用户不是提升的管理员。没有它,某些命令将无法正常工作。请确保该进程具有本地管理员权限和以管理员身份运行(UAC)。
2015-04-07 14:49:33:(INFO):类别:-Unknown Operation-:
2015-04-07 14:49:37 :(错误):类别:错误:失败在调用WS-Management时调用
2015-04-07 14:49:37 :(错误):类别:调用者未经授权。
2015-04-07 14:49:37 :(警告):类别: - 初始化连接 - :本地连接失败,将尝试使用远程服务器进行连接。
2015-04-07 14:49:41 :(错误):类别:LoadXMLFromFile:配置文件不包含强制标记。
2015-04-07 14:49:41 :(错误):类别:退出:***********退出代码38.详细信息:XML文件出错(可能的原因 - 文件不存在或拒绝访问;文件包含不正确的参数;加密密码/参数不正确或缺失;数据无效)





输出应采用以下格式:

 <   myfile  >  
< errorcode > 38 < /错误代码 >
< 错误 > 调用WS-Management调用失败.-初始化连接 - :本地连接失败,将尝试使用远程服务器连接。 LoadXMLFromFile:XML不包含XML文件的强制tag.Error(可能的原因 - 文件不存在或对它的访问被拒绝;文件包含不正确的参数;加密密码/参数不正确或缺失;数据无效)< / error >
< / myfile >

解决方案

))+,RegexOptions.None);
XElement xeRoot = new XElement( wpassetd); // 根节点
foreach (匹配m in expression.Matches(content))
{
XElement xeParent = new XElement(m.Groups [ ]值)。

string [] children = m.Groups [ children]。Value.Split(' '); // 将空格用作子项的分隔符

foreach (捕获上限 m.Groups [ values]。捕获)
{
XElement xeChild = new XElement( data); // 将名称child更改为任何合适的
string [] values = cap.Value.Split( new string [] { },StringSplitOptions.None);
// 检查子项和值计数是否相等
if (children.Length!= values.Length)
throw new 异常( 子项数和值不匹配。);

for int i = 0 ; i < children.Length; i ++)
{
XElement xeChildValue = new XElement(children [i] .ToLower());

// xeChildValue.Value = values [i];

// xeChildValue.Value = String.Format(![CDATA [{0}]] ,values [i]);
XCData cdata = new XCData(values [i]);
xeChildValue.Add(cdata);

xeChild.Add(xeChildValue);

}
xeParent.Add(xeChild);

}

xeRoot.Add(xeParent);
}
XDocument xmldoc = new XDocument();
string 结果;
xmldoc.Add(xeRoot);
xmldoc.Save(statusfilename);
result = Path.GetFileName(statusfilename);
// xmldoc.Save(@test.xml);





和我的文本文件是:

 2015 -04-07 14:49:33:(INFO):类别:HandleOutPut:开始登录2015-04-07 14:49:33 
2015-04-07 14:49:33 :(警告):类别:IsRunAsAdmin:运行此进程的用户不是提升的管理员。没有它,某些命令将无法正常工作。请确保该进程具有本地管理员权限和以管理员身份运行(UAC)。
2015-04-07 14:49:33:(INFO):类别:-Unknown Operation-:
2015-04-07 14:49:37 :(错误):类别:错误:失败在调用WS-Management时调用
2015-04-07 14:49:37 :(错误):类别:调用者未经授权。
2015-04-07 14:49:37 :(警告):类别: - 初始化连接 - :本地连接失败,将尝试使用远程服务器进行连接。
2015-04-07 14:49:41 :(错误):类别:LoadXMLFromFile:配置文件不包含强制标记。
2015-04-07 14:49:41 :(错误):类别:退出:***********退出代码38.详细信息:XML文件出错(可能的原因 - 文件不存在或拒绝访问;文件包含不正确的参数;加密密码/参数不正确或缺失;数据无效)





输出应采用以下格式:

 <   myfile  >  
< errorcode > 38 < /错误代码 >
< 错误 > 调用WS-Management调用失败.-初始化连接 - :本地连接失败,将尝试使用远程服务器连接。 LoadXMLFromFile:XML不包含XML文件的强制tag.Error(可能的原因 - 文件不存在或对它的访问被拒绝;文件包含不正确的参数;加密密码/参数不正确或缺失;数据无效)< / error >
< / myfile >


检查以下解决方案



http://stackoverflow.com/questions/15402493/convert-flat-text-file-to-xml-in-c-尖锐的 [ ^ ]

hey guys from using below code i tried to convert my text file to xml but i am not succeded with it yet. after lot many tries and efforts i thought to post it on code project. if possible please check my code and provide me related solution for the same.

string statusFilePath = Directory.GetCurrentDirectory().ToString() + "\\Status\\";
            foreach (string file in Directory.GetFiles(statusFilePath, "wpasset*.txt"))
               {
                   string filename = Path.GetFileNameWithoutExtension(file);
                string content = File.ReadAllText(file);
                string statusfilename = Directory.GetCurrentDirectory().ToString() + "\\\\Status\\\\" + "test.xml";

                // string statusFilePath1 = Directory.GetCurrentDirectory().ToString() + "\\\\Status\\\\" + "*.xml";
                Regex expression = new Regex(@"##(?<parent>\w+)\r\n(?<children>[\w ]+)\r\n((?<values>[\S ]+)(\r\n(?!#)|$))+", RegexOptions.None);
                XElement xeRoot = new XElement("wpassetd");   //root node
                foreach (Match m in expression.Matches(content))
                {
                    XElement xeParent = new XElement(m.Groups["parent"].Value);

                    string[] children = m.Groups["children"].Value.Split(' ');      // Use space as delimter for the children

                    foreach (Capture cap in m.Groups["values"].Captures)
                    {
                        XElement xeChild = new XElement("data");   // Change the name 'child' to whatever suitable
                        string[] values = cap.Value.Split(new string[] { ":" }, StringSplitOptions.None);
                        // Check that the children and values counts are equal
                        if (children.Length != values.Length)
                            throw new Exception("The number of children and values mismatch.");

                        for (int i = 0; i < children.Length; i++)
                        {
                            XElement xeChildValue = new XElement(children[i].ToLower());

                            //xeChildValue.Value = values[i];

                            //xeChildValue.Value = String.Format("![CDATA[{0}]]", values[i]);
                            XCData cdata = new XCData(values[i]);
                            xeChildValue.Add(cdata);

                            xeChild.Add(xeChildValue);

                        }
                        xeParent.Add(xeChild);

                    }

                    xeRoot.Add(xeParent);
                }
                XDocument xmldoc = new XDocument();
                string result;
                xmldoc.Add(xeRoot);
                xmldoc.Save(statusfilename);
                result = Path.GetFileName(statusfilename);
                //xmldoc.Save(@"test.xml");    



and my text file is :

2015-04-07 14:49:33:(INFO) : Category: HandleOutPut: Starting log 2015-04-07 14:49:33
2015-04-07 14:49:33:(WARN) : Category: IsRunAsAdmin: The user running this process is not an elevated administrator. Some commands will not work properly without it. Please make sure that the process has local administrator privileges and "Run as administrator"(UAC). 
2015-04-07 14:49:33:(INFO) : Category: -Unknown Operation-: 
2015-04-07 14:49:37:(ERROR) : Category: error: Failed while calling WS-Management call 
2015-04-07 14:49:37:(ERROR) : Category:The caller is unauthorized. 
2015-04-07 14:49:37:(WARN) : Category: -Initializing connection-: Failed connecting locally , will try to connect using the remote server. 
2015-04-07 14:49:41:(ERROR) : Category: LoadXMLFromFile: The profile does not contain the mandatory tag. 
2015-04-07 14:49:41:(ERROR) : Category: Exit: ***********Exit with code 38. Details: Error with XML file (possible reasons - the file does not exist or access to it is denied; the file contains incorrect parameters; incorrect or missing encryption password/parameter; invalid data)    



output should be in following format:

<myfile>
<errorcode>38</errorcode>
<error>Failed while calling WS-Management call.-Initializing connection-:Failed connecting locally , will try to connect using the remote server. LoadXMLFromFile: The XML does not contain the mandatory tag.Error with XML file (possible reasons - the file does not exist or access to it is denied; the file contains incorrect parameters; incorrect or missing encryption password/parameter; invalid data) </error>
</myfile>

解决方案

))+", RegexOptions.None); XElement xeRoot = new XElement("wpassetd"); //root node foreach (Match m in expression.Matches(content)) { XElement xeParent = new XElement(m.Groups["parent"].Value); string[] children = m.Groups["children"].Value.Split(' '); // Use space as delimter for the children foreach (Capture cap in m.Groups["values"].Captures) { XElement xeChild = new XElement("data"); // Change the name 'child' to whatever suitable string[] values = cap.Value.Split(new string[] { ":" }, StringSplitOptions.None); // Check that the children and values counts are equal if (children.Length != values.Length) throw new Exception("The number of children and values mismatch."); for (int i = 0; i < children.Length; i++) { XElement xeChildValue = new XElement(children[i].ToLower()); //xeChildValue.Value = values[i]; //xeChildValue.Value = String.Format("![CDATA[{0}]]", values[i]); XCData cdata = new XCData(values[i]); xeChildValue.Add(cdata); xeChild.Add(xeChildValue); } xeParent.Add(xeChild); } xeRoot.Add(xeParent); } XDocument xmldoc = new XDocument(); string result; xmldoc.Add(xeRoot); xmldoc.Save(statusfilename); result = Path.GetFileName(statusfilename); //xmldoc.Save(@"test.xml");



and my text file is :

2015-04-07 14:49:33:(INFO) : Category: HandleOutPut: Starting log 2015-04-07 14:49:33
2015-04-07 14:49:33:(WARN) : Category: IsRunAsAdmin: The user running this process is not an elevated administrator. Some commands will not work properly without it. Please make sure that the process has local administrator privileges and "Run as administrator"(UAC). 
2015-04-07 14:49:33:(INFO) : Category: -Unknown Operation-: 
2015-04-07 14:49:37:(ERROR) : Category: error: Failed while calling WS-Management call 
2015-04-07 14:49:37:(ERROR) : Category:The caller is unauthorized. 
2015-04-07 14:49:37:(WARN) : Category: -Initializing connection-: Failed connecting locally , will try to connect using the remote server. 
2015-04-07 14:49:41:(ERROR) : Category: LoadXMLFromFile: The profile does not contain the mandatory tag. 
2015-04-07 14:49:41:(ERROR) : Category: Exit: ***********Exit with code 38. Details: Error with XML file (possible reasons - the file does not exist or access to it is denied; the file contains incorrect parameters; incorrect or missing encryption password/parameter; invalid data)    



output should be in following format:

<myfile>
<errorcode>38</errorcode>
<error>Failed while calling WS-Management call.-Initializing connection-:Failed connecting locally , will try to connect using the remote server. LoadXMLFromFile: The XML does not contain the mandatory tag.Error with XML file (possible reasons - the file does not exist or access to it is denied; the file contains incorrect parameters; incorrect or missing encryption password/parameter; invalid data) </error>
</myfile>


check the below solution

http://stackoverflow.com/questions/15402493/convert-flat-text-file-to-xml-in-c-sharp[^]


这篇关于在C#中将文本转换为xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆