簡體   English   中英

創建動態xml文件

[英]Creating dynamic xml file

我想使用C#代碼創建1095個電子文件xml。 為此,我要創建動態標簽,這意味着如果數據可用,則僅創建標簽,否則無法顯示該標簽。

這是使用xml linq創建xml文件的示例。 您可以根據需要添加IF語句以跳過添加任何元素

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string header = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><root xmlns:irs=\"myUrl\"></root>";

            XDocument doc = XDocument.Parse(header);
            XElement root = doc.Root;
            XNamespace irs = root.GetNamespaceOfPrefix("irs");

            XElement businessName = new XElement("BusinessNameLine1Txt", "Comp Name");
            root.Add(businessName);

            XElement tinRequest = new XElement(irs + "TINRequestTypeCd");
            root.Add(tinRequest);

            XElement employerEIN = new XElement(irs + "EmployerEIN", "899090900");
            root.Add(employerEIN);

            XElement contactNameGrp = new XElement("ContactNameGrp");
            root.Add(contactNameGrp);

            XElement firstName = new XElement("PersonFirstNm", "First Name Person");
            contactNameGrp.Add(firstName);

            XElement lastName = new XElement("PersonLastNm", "Last Name Person");
            contactNameGrp.Add(lastName);
        }
    }
}
//sample output
//<?xml version="1.0" encoding="utf-8" ?>
//<root xmlns:irs="myUrl">
//<BusinessName>
//  <BusinessNameLine1Txt>Comp Name</BusinessNameLine1Txt>
//</BusinessName> 
//<irs:TINRequestTypeCd>BUSINESS_TIN</irs:TINRequestTypeCd> 
//<irs:EmployerEIN>899090900</irs:EmployerEIN> 
//<ContactNameGrp>
//  <PersonFirstNm>First Name Person</PersonFirstNm>
//  <PersonLastNm>Last Name Person</PersonLastNm>
//</ContactNameGrp> <ContactPhoneNum>9090909000</ContactPhoneNum>
//</root>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM