2016-05-10 3 views
0

В настоящее время я пытаюсь перевести часть библиотеки Java в библиотеку C# для использования в Unity. В этой Java-библиотеке некоторые классы генерируются из файлов XML, чьи файлы .xml у меня есть, но так как я никогда не делал ничего подобного, ни на Java, ни на C#.XML-синтаксис для генерации кода C#

Я занимаюсь некоторыми исследованиями, и я нашел различные способы преобразования этих .xml-файлов в классы .cs, но я не могу найти документацию о синтаксисе, который должен иметь XML-файл.

Я пытался использовать xsd.exe инструмент и мне удалось создать и XSD файл из одного XML-файл, но когда я попытался сгенерировать файл в .cs я propted эту ошибку: Error: Can only generate one of classes or datasets.

затем я сделал некоторые исследования и обнаружили еще один инструмент, Xsd2Code, так что я пытался использовать его с тем же XML-файлов, чтобы получить файл .cs, но это побудило ошибку, жалуясь о структуре:

C:\Program Files (x86)\Xsd2Code>Xsd2Code.exe Vehicle.xml Vehicle.cs 

Xsd2Code Version 3.4.0.32990 
Code generation utility from XML schema files. 

Error: Declaración XML inesperada. La declaración XML debe ser el primer nodo del documento y no pueden aparecer espacios en blanco delante. Línea 2, posición 3. 
     SubType: Unspecified 

     Rule: 

Я переведет его, так как оно на испанском языке: Ошибка: Неожиданное объявление XML. Объявление XML должно быть первым узлом и не должно содержать пробелов раньше. Линия 2, позиция 3.

Это первые строки конкретного файла:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:hfp="http://www.w3.org/2001/XMLSchema-hasFacetAndProperty" targetNamespace="http://www.w3.org/2001/XMLSchema" blockDefault="#all" elementFormDefault="qualified" version="1.0" xml:lang="EN"> 
<?xml version="1.0" encoding="UTF-8"?> 
<traciClass> 
    <name>Vehicle</name> 

EDIT: Я исправил это как первый комментарий говорит, но теперь я получаю

Error: Schema validation failed: 
El elemento 'traciClass' no es compatible en este contexto. 
     SubType: Unspecified 

     Rule: 

The element traciClass is not compatible in this context. 

Оригинальная почта продолжает:

Это шаблон того, как различные объекты должны быть определены в XML для Java, но мне интересно, будет ли эта структура изменяться для C#.

<?xml version="1.0" encoding="UTF-8"?> 
<!-- This file is used to generate a Java class with the same name for a 
    TraCI object. This saves manually writing a lot of boilerplate code. --> 
<traciClass> 
    <!-- The name of the object. It will be used as the class name. First letter 
     is capital. Must be equal to this document's file name. --> 
    <name>ExampleTraciObject</name> 

    <!-- The javadoc of the class that will be generated. --> 
    <javadoc> 
    Put your object description here. 
    </javadoc> 

    <!-- Lists all the other repositories that are needed by the queries --> 
    <repos> 
     <repo>Repository1</repo> 
     <repo>Repository2</repo> 
    </repos> 

    <command>it.polito.appeal.traci.protocol.Constants.CMD_GET_VEHICLE_VARIABLE</command> 

    <!-- List of all "read" queries, i.e. those that don't change the state 
     of the object and return a value --> 
    <readQueries> 

     <readQuery> 

      <!-- The name of the query. If the name is XXX, the Java class will contain 
       a method named queryXXX() --> 
      <name>ReadSomeValueQuery</name> 

      <!-- The enum name of the query. It will appear as an enum entry 
      in the inner Variable enum, and can be used with the getReadQuery() method --> 
      <enum>SOME_VALUE</enum> 

      <!-- A numeric value or a constant of type int that tells the variable 
       ID --> 
      <const>it.polito.appeal.traci.protocol.Constants.SOME_VARIABLE</const> 

      <!-- The Java class name that can make the query. It must be a subclass 
       of ReadObjectVarQuery. If the class is on the package 
       it.polito.appeal.traci, the package name can be omitted--> 
      <query>ReadObjectVarQuery.IntegerQ</query> 

      <!-- The return type of the query. It must be the same type (or a supertype) 
       of the type parameter V specified in the above class. 
       Leave it empty to use the query class as the return type. --> 
      <returnType>java.lang.Integer</returnType> 

      <!-- If true, it means that this value may change at every simulation 
       step. --> 
      <dynamic>true</dynamic> 
     </readQuery> 

     <!-- add other read queries here --> 
    </readQueries> 

    <!-- List of all "change state" queries, i.e. those that change the state 
     of the object and don't return a value --> 
    <changeStateQueries> 

     <!-- The syntax of a changeStateQuery is similar to readQuery, differences 
      are listed below. --> 
     <changeStateQuery> 
      <name>DoSomething</name> 
      <query>DoSomethingQuery</query> 
      <!-- Lists the read queries that may be changed by the execution of this 
      query, identified by their name. Calling this query will clear the caches 
      of the queries contained here. --> 
      <affects> 
       <affect>ReadSomeValueQuery</affect> 
      </affects> 
     </changeStateQuery> 

     <!-- add other change state queries here --> 

    </changeStateQueries> 

</traciClass> 

Это проблема синтаксиса XML?

+0

'' Должна быть первой строкой в ​​файле. Это именно то, что «объявление XML должно быть первым узлом и не должно содержать пробелов раньше». пытается рассказать вам :) – Fildor

+0

Я отредактирую свое сообщение. Я изменил это, и теперь он говорит: «traciClass несовместим в этом контексте» – Biurrun

+0

Я хочу, чтобы вы преобразовали его в формат, который ожидает ваш генератор кода C#. Например, «javadoc» будет очевидным случаем тега, который бесполезен для C#, но, вероятно, просто нуждается в переименовании. – Fildor

ответ

1

xsd.exe и xsd2Code могут быть использован для создания C# классов из XML-схем (обычно с расширением .xsd, отсюда и название инструмента). Они не будут генерировать классы непосредственно из образца XML экземпляра.

В xsd.exedocs вы можете использовать его для вывода схемы из экземпляра XML. Затем вы можете генерировать классы из этого.

xsd.exe instance.xml 
xsd.exe instance.xsd /classes 

Visual Studio также может помочь вам с этим: скопировать XML в буфер обмена и нажмите Edit | Paste Special | Paste XML as Classes.

+0

Два комментария по этому поводу: Во-первых, по какой-то причине, когда я делаю «Редактировать -> Вставить специальные -> Вставить XML Классы 'это не работает. Любое сообщение, предупреждение или что-либо запрашивается, но ничего не вставлено. Во-вторых, я также прочитал, что xsd.exe можно использовать для создания файла .xsd из XML-файла, верно? – Biurrun

+0

[Это работает для меня] (http://pastebin.com/jQUgGy2H). Вы правы, выводя xsd из xml - я обновил свой ответ. Кажется, вам нужно сделать это в два шага. –

+0

Mmm ... Я получаю эту ошибку при выполнении 'xsd.exe Vehicle.xml Ошибка: ошибка al procesar 'Vehicle.xml'. - El elemento 'traciClass' no es compatible en este contexto.' – Biurrun

Смежные вопросы