C#XML标记到CSV

时间:2019-03-05 09:17:22

标签: c# xml csv

我已经用以下格式(简短示例)提交了许多XML文件:

<namespace name="Colors">
    <green>
        <en>Green</en>
        <de>Gruen</de>
    </green>
    <blue>
        <en>Blue</en>
        <de>Blau</de>
    </blue>
    <namespace name="Subcolors">
        <perlwhite>
            <en>Perl White</en>
            <de>Perlweis</de>
        </perlwhite>
        <racingblack>
            <en>Racing Black</en>
            <de>Rennschwarz</de>
        </racingblack>
    </namespace>
</namespace>

我必须提取所有语言标签并将其以这种格式输出到csv文件中:

en;de;
Green;Gruen;
Blue;Blau;
Perl White;Perlweiß;
Racing Black;Renn Schwarz;

然后,我将这个CSV文件交给翻译。翻译后,在CSV文件中添加了一种新语言,例如法语:

en;de;fr;
Green;Gruen;Vert;
Blue;Blau;Bleu;
Perl White;Perlweiß;Perl Blanc;
Racing Black;Rennschwarz;Courses Noir;

然后我需要再次读取此csv文件,并将所有标签附加到所有相应的xml文件中,如下所示:

<namespace name="Colors">
    <green>
        <en>Green</en>
        <de>Gruen</de>
        <fr>Vert</fr>
    </green>
    <blue>
        <en>Blue</en>
        <de>Blau</de>
        <fr>Bleu</fr>
    </blue>
    <namespace name="Subcolors">
        <perlwhite>
            <en>Perl White</en>
            <de>Perlweis</de>
            <fr>Perl Blanc</fr>
        </perlwhite>
        <racingblack>
            <en>Racing Black</en>
            <de>Renn Schwarz</de>
            <fr>Courses Noir</fr>
        </racingblack>
    </namespace>
</namespace>

名称空间或其他节点(此处未列出,例如“多色”,“彩色”等)可以嵌套一次以上。并非每个文件都包含每个节点。并不是每个节点都以相同的方式嵌套在每个xml文件中。那从文件到文件是不同的。但是最后,每个分支都以几个语言标签结尾。这些都需要阅读和更新。

因此xml文件如下所示:

<namespace name="Colors">
    <green>
        <en>Green</en>
        <de>Gruen</de>
    </green>
    <blue>
        <en>Blue</en>
        <de>Blau</de>
    </blue>
        <namespace name="Subcolors">
            <perlwhite>
                <en>Perl White</en>
                <de>Perlweis</de>
            </perlwhite>
            <racingblack>
                <en>Racing Black</en>
                <de>Rennschwarz</de>
            </racingblack>
            <colored>
                <namespace name="Misc">
                    <fruits>
                        <apple>
                            <de>Apfel</de>
                            <en>Apple</en>
                        </apple>
                        <orange>
                            <de>Orange</de>
                            <en>Orange</en>
                        </orange>
                    </fruits>
                    <vegetables>
                        <cucumber>
                            <en>Cucumber</en>
                            <de>Gurke</de>
                        </cucumber>
                    </vegetables>
                    <namespace name="Other">
                        <othertag>
                            <entry>
                                <en>Entry</en>
                                <de>Eintrag</de>
                            </entry>
                        </othertag>
                    </namespace>
                </namespace>
            </colored>
        </namespace>
    </namespace>

因此,并非每个xml文件都是相同的,并且有不同的节点嵌套了不同的标记名。但是每个分支都以语言标签结尾。

有人可以帮我用C#简单地做到这一点吗?也许有两个简单的函数,例如Import(readCsvPath,appendXmlPath)和Export(readXmLPath,writeCsvPath)。

2 个答案:

答案 0 :(得分:1)

该代码基本上可以解决问题。原始xml具有perlwhite,但是新的csv具有Perl-White。您如何知道将破折号放在哪里。我将小p转换为大P,但不知道将破折号放在哪里。

public class HttpRequest {
public static enum Method {
    POST, PUT, DELETE, GET;
}

private URL url;
private HttpURLConnection con;
private OutputStream os;

//After instantiation, when opening connection - IOException can occur
public HttpRequest(URL url) throws IOException {
    this.url = url;
    con = (HttpURLConnection) this.url.openConnection();
}

//Can be instantiated with String representation of url, force caller to check for IOException which can be thrown
public HttpRequest(String url) throws IOException {
    this(new URL(url));
    Log.d("parameters", url);
}

/**
 * Sending connection and opening an output stream to server by pre-defined instance variable url
 *
 * @param //isPost boolean - indicates whether this request should be sent in POST method
 * @throws IOException - should be checked by caller
 */
private void prepareAll(Method method) throws IOException {
    con.setDoInput(true);
    con.setRequestMethod(method.name());
    if (method == Method.POST || method == Method.PUT) {
        con.setDoOutput(true);
        os = con.getOutputStream();
    }
}

//prepare request in GET method
//@return HttpRequest this instance -> for chaining method @see line 22
public HttpRequest prepare() throws IOException {
    prepareAll(Method.GET);
    return this;
}

/**
 * Prepares HttpRequest method with for given method, possible values: HttpRequest.Method.POST,
 * HttpRequest.Method.PUT, HttpRequest.Method.GET & HttpRequest.Method.DELETE
 *
 * @param method HttpRequest.Method - nested enum HttpRequest.Method constant
 * @return HttpRequest this instance -> for chaining method @see line 22
 * @throws IOException - should be checked by caller
 */
public HttpRequest prepare(Method method) throws IOException {
    prepareAll(method);
    return this;
}

/**
 * Adding request headers (standard format "Key":"Value")
 *
 * @param headers String variadic params in standard format "Key":"Value"
 * @return HttpRequest this instance -> for chaining method @see line 22
 */
public HttpRequest withHeaders(String... headers) {
    for (int i = 0, last = headers.length; i < last; i++) {
        String[] h = headers[i].split("[:]");
        con.setRequestProperty(h[0], h[1]);
    }
    return this;
}

/**
 * Writes query to open stream to server
 *
 * @param query String params in format of key1=v1&key2=v2 to open stream to server
 * @return HttpRequest this instance -> for chaining method @see line 22
 * @throws IOException - should be checked by caller
 */
public HttpRequest withData(String query) throws IOException {
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(query);
    writer.close();
    return this;
}

/**
 * Builds query on format of key1=v1&key2=v2 from given hashMap structure
 * for map: {name=Bubu, age=29} -> builds "name=Bubu&age=29"
 * for map: {Iam=Groot} -> builds "Iam=Groot"
 *
 * @param params HashMap consists of key-> value pairs to build query from
 * @return HttpRequest this instance -> for chaining method @see line 22
 * @throws IOException - should be checked by caller
 */
public HttpRequest withData(HashMap<String, String> params) throws IOException {
    StringBuilder result = new StringBuilder();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        result.append((result.length() > 0 ? "&" : "") + entry.getKey() + "=" + entry.getValue());//appends: key=value (for first param) OR &key=value(second and more)
        Log.d("parameters", entry.getKey() + "  ===>  " + entry.getValue());
    }
    withData(result.toString());
    return this;
}

//When caller only need to send, and don't need String response from server
public int send() throws IOException {
    return con.getResponseCode(); //return HTTP status code to indicate whether it successfully sent
}

/**
 * Sending request to the server and pass to caller String as it received in response from server
 *
 * @return String printed from server's response
 * @throws IOException - should be checked by caller
 */
public String sendAndReadString() throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
    StringBuilder response = new StringBuilder();
    for (String line; (line = br.readLine()) != null; ) response.append(line + "\n");
    Log.d("ressss", response.toString());
    return response.toString();
}

/**
 * Sending request to the server and pass to caller its raw contents in bytes as it received from server.
 *
 * @return byte[] from server's response
 * @throws IOException - should be checked by caller
 */
public byte[] sendAndReadBytes() throws IOException {
    byte[] buffer = new byte[8192];
    InputStream is = con.getInputStream();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    for (int bytesRead; (bytesRead = is.read(buffer)) >= 0; ) output.write(buffer, 0, bytesRead);
    return output.toByteArray();
}

//JSONObject representation of String response from server
public JSONObject sendAndReadJSON() throws JSONException, IOException {
    return new JSONObject(sendAndReadString());
}
}

答案 1 :(得分:0)

要将XML导入CSV文件,您可以使用以下代码,该代码并不冗长又简单:

export class ChildComponent implements OnInit, AfterViewInit {

  displayedColumns = ['idsignalement', 'nom', 'description', 'descriptionlieu', 'date', 'x', 'y'];
  signalementsDataSource = new MatTableDataSource<Signalement>();

  @Input() signalements: Signalement[];
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor() { }

  ngOnInit(): void {
    this.signalementsDataSource.data = this.signalements;
  }

  ngAfterViewInit() {
    console.log(this.signalements);
    this.signalementsDataSource.paginator = this.paginator;
    this.signalementsDataSource.sort = this.sort;
  }

以另一种方式,将CSV转换为XML需要更多的编码,因为您将必须检测每个要翻译的节点并添加另一个代表新语言的节点。这需要更多的编码,而且回答的范围太广-您必须先自己编写一些代码,然后再返回有关您可能遇到的问题的更精确的问题。

祝你好运。