简体   繁体   中英

Best way to convert ASCII txt file to XML within VB.NET, C# or Javascript?

I'm not exactly sure if this is the correct question to be asked but I will tell you what I am attempting. I have an ASCII txt file with product data in it. It does not have headers. I am looking for a way to convert this data into an XML file, however, I want it to parse through one of the txt fields to incorporate a look-up field and modify the data based on that field. Now I could use VB.NET, C# or Javascript. Example provided:

Example ASCII Data:

ACE14       1016    ACP, Inc.   Amana® Commercial Convection Express™ Combination Oven
AOC24       1016    ACP, Inc.   Amana® Commercial Microwave Oven, 2400 watts

Example XML I need based off example given (it would look up info based on 'ACP, Inc.')

<xml>
  <Product>
     <ProductManufacturer>ACP, Inc.</ProductManufacturer>
     <ProductCode>AMN-ACE14</ProductCode>
     <ProductTitle>Amana Commercial Convection Express Combination Oven</ProductTitle>
  </Product>
<Product>
     <ProductManufacturer>ACP, Inc.</ProductManufacturer>
     <ProductCode>AMN-AOC24</ProductCode>
     <ProductTitle>Amana Commercial Microwave Oven</ProductTitle>
  </Product>

Anyone direct me to some good samples? It would give me a good start. Thanks.

Here is one simple solution, but as I hinted in the comments, there really are a lot of ways to do this. Pick one based on your requirements (is reading different filetypes like this in slightly different formats a requirement - then go for a library).

var lines = File.ReadAllLines("D:\\test.txt");
var products = from line in lines
               select new 
               {
                    ProductManufacturer = line.Substring(0,12).Trim(),
                    ProductCode = line.Substring(12, 8).Trim(),
                    Description = line.Substring(20).Trim()
               };              

var xml = new XDocument(new XElement("xml", 
    from p in products
    select new XElement("Product",
        new XElement("ProductManufacturer", p.ProductManufacturer),
        new XElement("ProductCode", p.ProductCode),
        new XElement("Description", p.Description))));

You could also consider creating a Product class, and then use XML Serialization instead of specifying the format in code. This is likely to be a good idea if you need to work with Product entities often.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM