简体   繁体   中英

How to convert a string to xml in C#.net

How to convert a string to required xml format in c#.net

If suppose we are having data in string as

"XXXX
YYYY
ZZZZ
CCCC" 

I have required output like based on each and every row should generate with name of

Example

<filed1>XXXX></Filed1>
<filed2>YYYY></Filed2>
<filed3>ZZZZ></Filed3>
<filed4>CCCC></Filed4>

You can use LINQ to XML to build XML documents in a very elegant way:

string data = "XXXX YYYY ZZZZ CCCC";

XDocument doc =
    new XDocument(
        new XElement("root",
            data.Split()
                .Select((item, pos) => new XElement("filed" + (pos + 1), item))
        )
    );

Console.WriteLine(doc);

Output:

<?xml version="1.0"?>
<root>
    <filed1>XXXX</filed1>
    <filed2>YYYY</filed2>
    <filed3>ZZZZ</filed3>
    <filed4>CCCC</filed4>
</root>

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