0

我有一个.txt文件,我必须在文件中更改它xml。我的.txt文件是pipe-delimited ("|", vertical bar)纯文本文件。像这样:

169055|759656025621|Dos|Justamente Tres|Kill Rock Stars|256|PUNK|CD-JEWEL CASE|06/24/1996|D

现在我必须将此文本文件更改为 xml 文件,并且我必须为此 xml 添加父子节点。我必须使用 Linq to xml 和 XElement。请帮帮我。

4

2 回答 2

1
//path of your RDF file i.e. txt file used delimeter |

String filePath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, @"RdfFile/RDF.txt");

IEnumerable<String> source = File.ReadLines(filePath);

 XElement scans = new XElement("Test",


        from str in source
        let fields = str.Split('|')
        select new XElement("Product",
           new XAttribute("Action", FileName),
           new XAttribute("EnsureDefaultVariant", "1"),
           new XAttribute("ID", fields[0]),



            new XElement("Summary", fields[2]),
            new XElement("ImageFilenameOverride", fields[1])


            )

    );
//path in which xml file you want to save result.

 String filePath_Xml = Path.Combine(HostingEnvironment.ApplicationPhysicalPath,
 @"XMLFile/RDF__Scans_Add_XMLFile.xml");

 scans.Save(filePath_Xml);
于 2013-03-29T07:38:25.833 回答
0

将您的输入文本文件作为c:\sample.txt. 包含如下行(分隔符的数量可能会有所不同,每条记录都会产生或多或少的字段):

169055|759656025621|Dos|Justamente Tres|Kill Rock Stars|256|PUNK|CD-JEWEL CASE|06/24/1996|D
xx|xx|xx|xx|xx|xx|xx|xx|xx|xx
...

然后你可以这样开始:

public static void Main() {
            XElement root = new XElement("root");//create a root node
            foreach (String ln in File.ReadAllLines(@"c:\sample.txt")){//<-- read lines
                string[] fields = ln.Split('|'); //<-- change field separator here & split fields
                XElement record = new XElement("record"); //create a child node (i.e., parent of filelds)
                int pos = 0;
                foreach (String sp in fields){
                    pos += 1;
                    XElement field = new XElement(string.Format("field_{0}", pos.ToString())); // prepare child nodes
                    field.Add(sp);
                    record.Add(field); // add to parent node
                }
                root.Add(record); // add to root
            }
            Console.Write (root.ToString());  // display the result on console
            Console.ReadKey(); // waiting for you........
        }

控制台上的结果:

<root>
  <record>
    <field_1>169055</field_1>
    <field_2>759656025621</field_2>
    <field_3>Dos</field_3>
    <field_4>Justamente Tres</field_4>
    <field_5>Kill Rock Stars</field_5>
    <field_6>256</field_6>
    <field_7>PUNK</field_7>
    <field_8>CD-JEWEL CASE</field_8>
    <field_9>06/24/1996</field_9>
    <field_10>D</field_10>
  </record>
  <record>
    <field_1>xx</field_1>
    <field_2>xx</field_2>
    <field_3>xx</field_3>
    <field_4>xx</field_4>
    <field_5>xx</field_5>
    <field_6>xx</field_6>
    <field_7>xx</field_7>
    <field_8>xx</field_8>
    <field_9>xx</field_9>
    <field_10>xx</field_10>
  </record>
</root>

希望这可以帮助。

于 2013-03-14T15:10:34.710 回答